<script type="text/x-template" id="themes-github">
    <div class="github-themes-page">
        <div class="gh-header">
            <div class="row">
                <div class="col nopadding">
                    <h1 class="header-text">{{$root.getLz('settings.header.visual.theme.github.page')}}</h1>
                </div>
                <div class="col-auto nopadding flex-center">
                    <button class="md-btn md-btn-small md-btn-block" @click="$root.openSettingsPage('styles')">
                        {{$root.getLz('settings.option.visual.theme.manageStyles')}}
                    </button>
                </div>
                <div class="col-auto flex-center">
                    <button class="md-btn md-btn-small md-btn-block" @click="$root.checkForThemeUpdates()">
                        {{ $root.getLz('settings.option.visual.theme.checkForUpdates') }}
                    </button>
                </div>
                <div class="col-auto nopadding flex-center">
                    <button class="md-btn md-btn-small md-btn-block" @click="installThemeURL()">
                        {{$root.getLz('settings.option.visual.theme.github.download')}}
                    </button>
                </div>
            </div>
        </div>
        <div class="gh-content">
            <div class="repos-list">
                <ul class="list-group list-group-flush">
                    <li @click="showRepo(repo)" class="list-group-item list-group-item-dark"
                        :style="{'background': (repo.id == openRepo.id) ? 'var(--keyColor)' : ''}"
                        v-for="repo in repos">
                        <div class="row">
                            <div class="col flex-center">
                                <div>
                                    <h4 class="repo-name">{{ (repo.description != null) ? repo.description :
                                        repo.full_name }}</h4>
                                    <div>⭐ {{ repo.stargazers_count }}</div>
                                </div>
                            </div>
                            <div class="col-auto">
                                <span v-if="themesInstalled.includes(repo.full_name.toLowerCase())"
                                      class="codicon codicon-cloud-download"></span>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>

            <div class="github-preview" v-if="openRepo.full_name">
                <div class="gh-preview-header">
                    <div class="row nopadding">
                        <div class="col nopadding flex-center">
                            <div>
                                <h3 class="repo-preview-name">{{ openRepo.description }}</h3>
                                <div>
                                    <div class="svg-icon inline"
                                         :style="{'--url': 'url(\'./assets/github.svg\')'}"></div>
                                    <a class="repo-url" target="_blank" :href="openRepo.html_url">{{ openRepo.full_name
                                        }}</a></div>
                                <div>⭐ {{ openRepo.stargazers_count }}</div>
                            </div>
                        </div>
                        <div class="col-auto nopadding flex-center">
                            <button class="md-btn md-btn-primary" @click="installThemeRepo(openRepo)">
                                <span v-if="!themesInstalled.includes(openRepo.full_name.toLowerCase())">{{$root.getLz('action.install')}}</span>
                                <span v-else>{{$root.getLz('action.update')}}</span>
                            </button>
                        </div>
                    </div>
                </div>
                <hr>
                <div v-html="openRepo.readme" class="github-content"></div>
            </div>
            <div class="github-preview" v-else>

            </div>
            </transition>
        </div>
    </div>
</script>
<script>
    Vue.component('themes-github', {
        template: "#themes-github",
        props: [],
        data: function () {
            return {
                repos: [],
                openRepo: {
                    id: -1,
                    name: '',
                    description: '',
                    html_url: '',
                    stargazers_count: 0,
                    owner: {
                        avatar_url: ''
                    },
                    readme: ""
                },
                themesInstalled: [],
                themes: []
            }
        },
        mounted() {
            this.themes = ipcRenderer.sendSync("get-themes")
            this.getRepos();
            this.getInstalledThemes();
        },
        methods: {
            openThemesFolder() {
                ipcRenderer.invoke("open-path", "themes")
            },
            getInstalledThemes() {
                let self = this
                const themes = ipcRenderer.sendSync("get-themes")
                // for each theme, get the github_repo property and push it to the themesInstalled array, if not blank
                themes.forEach(theme => {
                    if (theme.github_repo !== "" && typeof theme.commit != "") {
                        self.themesInstalled.push(theme.github_repo.toLowerCase())
                    }
                })
            },
            showRepo(repo) {
                const self = this
                const readmeUrl = `https://raw.githubusercontent.com/${repo.full_name}/main/README.md`;
                var requestOptions = {
                    method: 'GET',
                    redirect: 'follow'
                };

                fetch(readmeUrl, requestOptions)
                    .then(response => response.text())
                    .then(result => {
                        self.openRepo = repo
                        self.openRepo.readme = self.convertReadMe(result);
                    })
                    .catch(error => {
                        self.openRepo = repo
                        self.openRepo.readme = `This repository doesn't have a README.md file.`;
                        console.log('error', error)
                    });
            },
            convertReadMe(text) {
                return marked.parse(text)
            },
            installThemeRepo(repo) {
                let self = this
                let msg = app.stringTemplateParser(app.getLz('settings.option.visual.theme.github.install.confirm'), {
                    repo: repo.full_name
                });
                app.confirm(msg, (res) => {
                    if (res) {
                        ipcRenderer.once("theme-installed", (event, arg) => {
                            if (arg.success) {
                                self.themes = ipcRenderer.sendSync("get-themes")
                                self.getInstalledThemes()
                                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));
                            } else {
                                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));
                            }
                        });
                        ipcRenderer.invoke("get-github-theme", repo.html_url)
                    }
                })
            },
            installThemeURL() {
                let self = this
                app.prompt(app.getLz('settings.prompt.visual.theme.github.URL'), (result) => {
                    if (result) {
                        ipcRenderer.once("theme-installed", (event, arg) => {
                            if (arg.success) {
                                self.themes = ipcRenderer.sendSync("get-themes")
                                notyf.success(app.getLz('settings.notyf.visual.theme.install.success'));
                            } else {
                                notyf.error(app.getLz('settings.notyf.visual.theme.install.error'));
                            }
                        });
                        ipcRenderer.invoke("get-github-theme", result)
                    }
                });
            },
            getRepos() {
                let self = this
                var requestOptions = {
                    method: 'GET',
                    redirect: 'follow'
                };

                fetch("https://api.github.com/search/repositories?q=topic:cidermusictheme fork:true&per_page=100", requestOptions)
                    .then(response => response.text())
                    .then(result => {
                        let items = JSON.parse(result).items
                        self.repos = items
                    })
                    .catch(error => console.log('error', error));
            }
        }
    })
</script>