<template>
    <div ref="main" class="main" @click="close">
        <div class="main" @click.stop>
            <Window @close="close">
                <template slot="header">
                    Последние 100 открытых книг
                </template>

                <el-table
                    :data="tableData"
                    style="width: 100%"
                    size="mini"
                    height="1px"
                    stripe
                    border
                    :default-sort = "{prop: 'touchDateTime', order: 'descending'}"
                    :header-cell-style = "headerCellStyle"
                    >

                    <el-table-column
                        prop="touchDateTime"
                        min-width="90px"
                        sortable
                        >
                        <template slot="header" slot-scope="scope"><!-- eslint-disable-line vue/no-unused-vars -->
                            Время<br>просм.
                        </template>
                        <template slot-scope="scope"><!-- eslint-disable-line vue/no-unused-vars -->
                            <div class="desc" @click="loadBook(scope.row.url)">
                                {{ scope.row.touchDate }}<br>
                                {{ scope.row.touchTime }}
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column
                        >
                        <template slot="header" slot-scope="scope"><!-- eslint-disable-line vue/no-unused-vars -->
                            <el-input
                                v-model="search"
                                size="mini"
                                style="margin: 0; padding: 0; vertical-align: bottom; margin-top: 10px"
                                placeholder="Найти"/>
                        </template>

                        <el-table-column
                            min-width="300px"
                            >
                            <template slot-scope="scope">
                                <div class="desc" @click="loadBook(scope.row.url)">
                                    <span style="color: green">{{ scope.row.desc.author }}</span><br>
                                    <span>{{ scope.row.desc.title }}</span>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column
                            min-width="100px"
                            >
                            <template slot-scope="scope">
                                <span class="clickable" @click="openOriginal(scope.row.url)">Оригинал</span><br>
                                <a :href="scope.row.path" :download="getFileNameFromPath(scope.row.path)">Скачать FB2</a>
                            </template>
                        </el-table-column>

                        <el-table-column
                            width="60px"
                            >
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    @click="handleDel(scope.row.key)">X
                                </el-button>
                            </template>
                        </el-table-column>

                    </el-table-column>

                </el-table>
            </Window>
        </div>
    </div>
</template>

<script>
//-----------------------------------------------------------------------------
import Vue from 'vue';
import Component from 'vue-class-component';
import path from 'path';
import _ from 'lodash';

import {formatDate} from '../../../share/utils';
import Window from '../../share/Window.vue';

export default @Component({
    components: {
        Window,
    },
})
class HistoryPage extends Vue {
    search = null;

    created() {
        this.commit = this.$store.commit;
        this.reader = this.$store.state.reader;
    }

    get tableData() {
        const state = this.reader;
        let result = [];

        for (let bookKey in state.openedBook) {
            const book = state.openedBook[bookKey];
            let d = new Date();
            d.setTime(book.touchTime);
            const t = formatDate(d).split(' ');

            let perc = '';
            const p = (book.bookPosSeen ? book.bookPosSeen : (book.bookPos ? book.bookPos : 0));
            if (book.textLength)
                perc = ` [${((p/book.textLength)*100).toFixed(2)}%]`;

            result.push({
                touchDateTime: book.touchTime,
                touchDate: t[0],
                touchTime: t[1],
                desc: {
                    title: `"${book.fb2.bookTitle}"${perc}`,
                    author: _.compact([
                        book.fb2.lastName,
                        book.fb2.firstName,
                        book.fb2.middleName
                    ]).join(' '),
                },
                url: book.url,
                path: book.path,
                key: book.key,
            });
        }

        const search = this.search;
        return result.filter(item => {
            return !search ||
                item.touchTime.includes(search) ||
                item.desc.title.toLowerCase().includes(search.toLowerCase()) ||
                item.desc.author.toLowerCase().includes(search.toLowerCase())
        });
    }

    headerCellStyle(cell) {
        let result = {margin: 0, padding: 0};
        if (cell.columnIndex > 0) {
            result['border-bottom'] = 0;
        }
        if (cell.rowIndex > 0) {
            result.height = '0px';
            result['border-right'] = 0;
        }
        return result;
    }

    getFileNameFromPath(fb2Path) {
        return path.basename(fb2Path).substr(0, 10) + '.fb2';
    }

    openOriginal(url) {
        window.open(url, '_blank');
    }

    openFb2(path) {
        window.open(path, '_blank');
    }

    handleDel(key) {
        this.commit('reader/delOpenedBook', {key});
    }

    loadBook(url) {
        this.$emit('load-book', {url});
        this.close();
    }

    close() {
        this.$emit('history-toggle');
    }

    keyHook(event) {
        if (event.type == 'keydown' && event.code == 'Escape') {
            this.close();
            return true;
        }
    }
}
//-----------------------------------------------------------------------------
</script>

<style scoped>
.main {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.header {
    margin: 0;
    padding: 0;
}

.clickable {
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}

.desc {
    cursor: pointer;
}
</style>