const Component = require(`vn-print/core/component`);
const emailBody = new Component('email-body');

module.exports = {
    name: 'osticket-report',
    async serverPrefetch() {
        const tickets = await this.fetchTickets();
        this.resolvedTickets = tickets.length;

        const technicians = [];
        for (let ticket of tickets) {
            const technicianName = ticket.assigned;

            let technician = technicians.find(technician => {
                return technician.name == technicianName;
            });

            if (!technician) {
                technician = {
                    name: technicianName,
                    tickets: []
                };
                technicians.push(technician);
            }

            technician.tickets.push(ticket);
        }

        this.technicians = technicians.sort((acumulator, value) => {
            return value.tickets.length - acumulator.tickets.length;
        });

        if (!this.technicians)
            throw new Error('Something went wrong');
    },
    computed: {
        dated: function() {
            const filters = this.$options.filters;

            return filters.date(Date.vnNew(), '%d-%m-%Y');
        },
        startedTime: function() {
            return new Date(this.started).getTime();
        },
        endedTime: function() {
            return new Date(this.ended).getTime();
        }
    },
    methods: {
        fetchDateRange() {
            return this.findOneFromDef('dateRange');
        },
        async fetchTickets() {
            const {started, ended} = await this.fetchDateRange();
            this.started = started;
            this.ended = ended;

            const connection = await this.getConnection('osticket');
            return this.rawSqlFromDef('tickets', [started, ended], connection);
        }
    },
    components: {
        'email-body': emailBody.build(),
    },
    props: {}
};