"use strict";

const Request = require("request");
const console = require("gifer-console");
const Service = require('../service');
// const mcService = require('./mcService/mcServices').srv;
const fs      = require('fs');
const crypto  = require('crypto');
const commands= require('../cmd/cmd').CMD;
const moment  = require('moment');
const CRLF    = '\r\n';
const cList   = {
    "GetTelegramAttach": GetTelegramAttach
}

function fileTimeStamp(dd) {
    var now  = Service.utcTime(dd ? new Date(dd) : new Date(), true).split('.');
    // 0  1  2    3  4  5  6
    // dd.mm.yyyy.hh.nn.ss.zzz
    var diff = parseInt(now[6]) + parseInt(now[5])*1000 + parseInt(now[4])*1000*60 + parseInt(now[3])*1000*60*60;

    return diff + "." + moment(new Date(now[2], now[1], now[0], now[3], now[4], now[5])).diff(moment([1,1,-1]), 'days');
}

function GetTelegramAttach(_message, send){
    var sha1       = crypto.createHash('sha1');
    var message    = Service.StringToObj(_message);

    if (message && message.message){
        var UINFrom = message.UINFrom;
        var UINTo   = message.UINTo;

        message = message.message;

        var attachInfo = message.photo ? message.photo[message.photo.length - 1] : message.document;
        var msgType    = 0;
        var fileName   = "";

        // console.log("1: " + _message);

        if (message.photo) {
            // "file_id": "AgACAgIAAxkBAAIg1F-ZZ8a98B2Plf_Bo7hpVW4mKkG0AAKYrjEb2oXJSCKbyBe-oOlI5VsVlS4AAwEAAwIAA3kAAzLmBQABGwQ",
            // "file_unique_id": "AQAD5VsVlS4AAzLmBQAB",
            // "file_size": 115127,
            // "width": 1280,
            // "height": 700

            msgType  = commands.msgType.IMAGE;
            fileName = "telegram_image_" + attachInfo.file_unique_id + ".jpg";
        } else
        if (message.document) {
            // "file_name"     :"Price-h2fl-20-10-2020.pdf",
            // "mime_type"     :"application/pdf",
            // "file_id"       :"BQACAgIAAxkBAAIg1V-Zg7eJNKpZa9VnuVf-32IzovJ9AAI9CAAC2oXJSG_h7u0nQUnwGwQ",
            // "file_unique_id":"AgADPQgAAtqFyUg",
            // "file_size"     :248476

            msgType  = commands.msgType.FILE;
            fileName = attachInfo.file_name;
        }

        if (!MCServer.TelegramToken){
            console.err("GetTelegramAttach, haven't TelegramToken or its empty", console.logLevel.ERROR);
        } else
        if (attachInfo && attachInfo.file_id){
            new Promise(function (resolve, reject){
                var res     = "";
                var request = Request({
                    method: "GET",
                    // получение информации про прикрепленный файл и путь, по которому мы можем его скачать
                    url   : "https://api.telegram.org/bot" + MCServer.TelegramToken + "/getFile?file_id=" + attachInfo.file_id
                });

                request.on('data', function (chunk) {
                    res += chunk;
                });

                request.on('end', function () {
                    resolve(res);
                });

                request.on('error', function (err) {
                    reject(err);
                });
            })
            .then(function (_info){
                // "ok":true,
                // "result":{
                //     "file_id":"BQACAgIAAxkBAAIg01-ZZ3VYIl3VrcQ39wW1loQru7xIAAI9CAAC2oXJSG_h7u0nQUnwGwQ",
                //     "file_unique_id":"AgADPQgAAtqFyUg",
                //     "file_size":248476,
                //     "file_path":"documents/file_0.pdf"
                // }
                var info = Service.StringToObj(_info);

                // console.log("2: " + _info);

                if (info.ok){
                    var filePath = MCPathes.Files + info.result.file_id + (new Date).getTime();
                    var fileD    = fs.createWriteStream(filePath);
                    var request  = Request({
                        method: "GET",
                        // качаем прикрепленный файл
                        url   : "https://api.telegram.org/file/bot" + MCServer.TelegramToken + "/" + info.result.file_path
                    });

                    request.pipe(fileD);

                    request.on('data', function (chunk) {
                        sha1.update(chunk);
                    });

                    request.on('close', function () {
                        var hash = sha1.digest('hex');

                        // fileD.close();

                        fs.renameSync(filePath, MCPathes.Files + hash + "." + Service.ExtractFileExtension(info.result.file_path));

                        var resolution = "-";

                        if (attachInfo.width && attachInfo.height) {
                            resolution = attachInfo.width + "x" + attachInfo.height;
                        }

                        var out = JSON.stringify({
                            UINFrom : UINFrom,
                            UINTo   : UINTo,
                            Msg     : hash + CRLF + fileName + CRLF + fileTimeStamp() + CRLF + attachInfo.file_size + CRLF + resolution,
                            MsgType : msgType
                        });

                        console.log("3: " + out);

                        send(commands.ns_private_message + "=" + out);
                    });

                    request.on('error', function (err) {
                        console.err("GetTelegramAttach: " + err.message, console.logLevel.ERROR);
                    });
                } else {
                    console.err("GetTelegramAttach: " + _info, console.logLevel.ERROR);
                }
            })
            .catch(function (err){
                console.err("GetTelegramAttach: " + err.message, console.logLevel.ERROR);
            });
        }
    } else {
        console.err("GetTelegramAttach: message is not JSON object or not has message.message field", console.logLevel.ERROR);
    }
}

function runCommand(params, send){
    
    if (cList.hasOwnProperty(params.Cmd)){
        cList[params.Cmd](params.Data, send);
    } else {
        console.err("customCmd, unknown command: " + params.Cmd, console.logLevel.ERROR);
    }
}

exports.runCMD = runCommand;