/*
 * @Author: YeeChan
 * @Date: 2021-06-02 11:27:38
 * @Description: 
 */

'use strict';

let fs = require('fs');
let path = require('fire-path');

const images = Editor.require("packages://ccc-apk/node_modules/images");
const iconList = [
  // 安卓
  { url: path.join('android', 'mipmap-ldpi', 'ic_launcher.png'), width: 36, height: 36 },
  { url: path.join('android', 'mipmap-mdpi', 'ic_launcher.png'), width: 48, height: 48 },
  { url: path.join('android', 'mipmap-hdpi', 'ic_launcher.png'), width: 72, height: 72 },
  { url: path.join('android', 'mipmap-xhdpi', 'ic_launcher.png'), width: 96, height: 96 },
  { url: path.join('android', 'mipmap-xxhdpi', 'ic_launcher.png'), width: 144, height: 144 },
  { url: path.join('android', 'mipmap-xxxhdpi', 'ic_launcher.png'), width: 192, height: 192 },
  { url: path.join('android', 'playstore-icon.png'), width: 512, height: 512 },
  // IOS
  { url: path.join('ios', 'AppIcon.appiconset', "icon-20-ipad.png"), width: 20, height: 20 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-20@2x-ipad.png"), width: 40, height: 40 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-20@2x.png"), width: 40, height: 40 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-20@3x.png"), width: 60, height: 60 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-29-ipad.png"), width: 29, height: 29 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-29.png"), width: 29, height: 29 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-29@2x-ipad.png"), width: 58, height: 58 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-29@2x.png"), width: 58, height: 58 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-29@3x.png"), width: 87, height: 87 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-40.png"), width: 40, height: 40 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-40@2x.png"), width: 80, height: 80 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-40@3x.png"), width: 120, height: 120 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-60@2x.png"), width: 120, height: 120 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-60@3x.png"), width: 180, height: 180 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-76.png"), width: 76, height: 76 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-76@2x.png"), width: 152, height: 152 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-83.5@2x.png"), width: 167, height: 167 },
  { url: path.join('ios', 'AppIcon.appiconset', "icon-1024.png"), width: 1024, height: 1024 }
];

const project_studio = path.join("jsb-default", "frameworks", "runtime-src", "proj.android-studio");

Editor.Panel.extend({

  style: fs.readFileSync(Editor.url("packages://ccc-apk/panel/index.css"), "utf-8"),
  template: fs.readFileSync(Editor.url("packages://ccc-apk/panel/index.html"), "utf-8"),

  // method executed when template and styles are successfully loaded and initialized
  ready() {
    const app = new window.Vue({
      el: this.shadowRoot,
      created() {
        this.localPath = path.resolve(Editor.Project.path, "build-templates/apk/");
        this.contentsPath = Editor.url("packages://ccc-apk/Contents.json");
        this._panelCreated();
      },
      init() {
      },
      data: {
        cfgPath: Editor.url('packages://ccc-apk/config.json'),
        profile: null,
        contentsPath: '',
        localPath: '',

      },
      methods: {
        //保存配置
        saveProfile() {
          fs.writeFileSync(this.cfgPath, JSON.stringify(this.profile));
        },
        _panelCreated() {
          if (!fs.existsSync(this.cfgPath)) {
            let defaultData = {
              'package': '',
              'apkPath': '',
              'versionCode': '',
              'versionName': '',
              'gameName': '',
            }; // 你自己默认的数据
            fs.writeFileSync(this.cfgPath, JSON.stringify(defaultData));
          }
          this.profile = JSON.parse(fs.readFileSync(this.cfgPath, 'utf-8'));

        },
        //同步 gradle
        onBtnSyncGradle(event) {
          this.log("同步 gradle")
          if (this.profile.package == "" || this.profile.versionCode == "" || this.profile.versionName == "") {
            this.log("数据不完整")
            return;
          }
          // 同步读取
          let read_build_gradle = path.join(this.profile.apkPath, project_studio, "app", "build.gradle");
          if (fs.existsSync(read_build_gradle)) {
            let gradle_data = fs.readFileSync(read_build_gradle);

            let index_applicationId = gradle_data.indexOf("applicationId");
            let index_minSdkVersion = gradle_data.indexOf("minSdkVersion");

            let index_versionCode = gradle_data.indexOf("versionCode");
            let index_versionName = gradle_data.indexOf("versionName", index_versionCode);
            let index_multiDexEnabled = gradle_data.indexOf("multiDexEnabled", index_versionName);

            this.log("index_versionCode:" + index_versionCode)
            this.log("index_versionName:" + index_versionName)
            this.log("index_multiDexEnabled:" + index_multiDexEnabled)

            let str_gradle = gradle_data.toString();

            let applicationId = str_gradle.substring(index_applicationId, index_minSdkVersion);
            let versionCode = str_gradle.substring(index_versionCode, index_versionName);
            let versionName = str_gradle.substring(index_versionName, index_multiDexEnabled);

            let result = str_gradle.replace(applicationId, 'applicationId "' + this.profile.package + '"\n\t\t');
            result = result.replace(versionCode, 'versionCode ' + this.profile.versionCode + '\n\t\t');
            result = result.replace(versionName, 'versionName "' + this.profile.versionName + '"\n\t\t');

            fs.writeFileSync(read_build_gradle, result);

            this.log("同步gradle 成功" + read_build_gradle)
          } else {
            this.log("没有找到:" + read_build_gradle)
          }
          if (event) {
            this.saveProfile()
          }
        },
        //生成icon
        onBtnCreatorIcon(event) {
          this.log("生成icon")
          let iconPath = path.join(this.localPath, "icon.png")
          if (!fs.existsSync(iconPath)) {
            Editor.log("没有找到build-templates/apk/icon.png");
            return;
          }
          for (let i = 0; i < iconList.length; i++) {
            let icon = iconList[i];
            this.mgm(iconPath, path.join(this.localPath, icon.url), { width: icon.width, height: icon.height });
          }
          // IOS 描述文件
          fs.copyFileSync(this.contentsPath, path.join(this.localPath, 'ios', 'AppIcon.appiconset', 'Contents.json'));

          Editor.log("全部已完成,生成路径:" + this.localPath);
        },
        //同步icon
        onBtnSyncIcon(event) {
          this.log("同步icon")
          let tab = ["mipmap-hdpi", "mipmap-mdpi", "mipmap-xhdpi", "mipmap-xxhdpi"]
          for (let index = 0; index < tab.length; index++) {
            const element = tab[index];
            let read_icon = path.join(this.localPath, "android", element, "ic_launcher.png");
            let save_icon = path.join(this.profile.apkPath, project_studio, "res", element, "ic_launcher.png");
            this.copy_file(read_icon, save_icon, () => {
              this.log("同步icon成功:" + save_icon)
            });
          }
          if (event) {
            this.saveProfile()
          }
        },
        //同步string.xml
        onBtnSyncString(event) {
          this.log("同步string.xml")
          if (this.profile.gameName != "") {
            let strInfo = "<resources>\n"
            strInfo = strInfo + "    <string name=\"app_name\" translatable=\"false\">" + this.profile.gameName + "</string>\n";
            strInfo = strInfo + "<resources>\n";

            let save_values = path.join(this.profile.apkPath, project_studio, "res", "values", "strings.xml");

            if (fs.existsSync(save_values)) {
              fs.writeFileSync(save_values, strInfo);
              this.log("同步strings.xml成功:" + save_values)
            } else {
              this.log("不存在:" + save_values)
            }
          } else {
            this.log("游戏名字为null")
            return;
          }
          if (event) {
            this.saveProfile()
          }
        },
        //同步Appconfig.java
        onBtnSyncAppConfig(event) {
          this.log("同步Appconfig.java")
          let name = "AppConfig.java";
          //存的路径
          let save_appconfig = path.join(this.profile.apkPath, project_studio, "src", "org", "cocos2dx", "javascript", name);
          //读的路径
          let read_appconfig = path.join(this.localPath, name);
          if (fs.existsSync(read_appconfig)) {
            this.copy_file(read_appconfig, save_appconfig, () => {
              this.log("同步Appconfig.java成功" + save_appconfig)
            });
            if (event) {
              this.saveProfile()
            }
          } else {
            this.log("没有找到" + read_appconfig)
          }

        },
        //同步所有
        onBtnSyncAll(event) {
          this.onBtnSyncGradle()
          this.onBtnSyncIcon()
          this.onBtnSyncString()
          this.onBtnSyncAppConfig()
          this.log("全部完成")
          if (event) {
            this.saveProfile()
          }
        },
        //保存
        onBtnSave(event) {
          this.saveProfile();
        },
        log(str) {
          Editor.log(str)
        },
        copy_file(path1, path2, listener) {
          if (fs.existsSync(path1)) {
            if (fs.existsSync(path2)) {
              fs.writeFileSync(path2, fs.readFileSync(path1));
              listener();
            } else {
              this.log("不存在:" + path2)
            }
          } else {
            this.log("不存在:" + path1)
          }
        },

        mgm(src, dst, option) {
          let dstDir = path.parse(dst).dir;
          this.mkdir(dstDir);
          images(src)
            .size(option.width)
            .save(dst);
        },
        mkdir(dirName, mode) {
          if (fs.existsSync(dirName)) {
            return true;
          }
          if (this.mkdir(path.dirname(dirName), mode)) {
            fs.mkdirSync(dirName, mode);
            return true;
          }
        }
      }
    })
  },
});