const { app, dialog, net, Menu, nativeTheme, accelerator, Tray, globalShortcut, BrowserWindow, nativeImage, clipboard, Notification, ipcMain, shell, https, screen} = require('electron')
const path = require('path');
const sharp = require('sharp');
const fs = require('fs');
const { exec } = require('child_process');
const { url } = require('inspector');
const screenshot = require('desktop-screenshot');

// app.dock.hide()

let tray = null
var mainWindow = null ;  //声明要打开的主窗口


app.whenReady().then(() => {

  const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
  tray = new Tray(path.join(__dirname, 'icon-'+theme+'.png'))

  // 监听系统主题更改事件
  nativeTheme.on('updated', () => {
    // 根据当前系统主题设置图标
    const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
    tray.setImage(path.join(__dirname, 'icon-'+theme+'.png'))
  });

  auto_check_updates()
  welcome()
  const contextMenu = Menu.buildFromTemplate([
    { label: '📷 开始截图', type: 'normal', accelerator: 'Alt+A', click: () => {
      saveScreenshot()
    }},
    { label: '🖼 从剪贴板导入', type: 'normal', accelerator: 'Alt+L', click: () => {
        Screenshot_beautification()
    }},
    { label: '🔲 加个描边', type: 'normal', accelerator: 'Alt+M', click: () => {
      add_outline()
    }},
    { type: 'separator' },
    { 
      label: '🎁 分享给朋友', 
      type: 'normal', 
      click: () => {
        const textToCopy = '这是我之前说过很好用的截图优化工具，可以试试看。https://www.iproduct.cc'; // 你想要复制的文本
    
        // 使用 Electron 的 clipboard 模块复制文本到剪贴板
        clipboard.writeText(textToCopy);
    
        const notification = new Notification({
          title: '分享链接已复制',
          body: '你可以粘贴分享给你的小伙伴了~',
        });
        notification.show();
      }
    },
    { label: '🍠 关注小红书', type: 'normal', click: () => {
      shell.openExternal('https://www.xiaohongshu.com/user/profile/64fd59070000000005003b0c')
    }},
    // { label: '☄️ 加入iProduct', type: 'normal', click: () => {
    //   shell.openExternal('https://www.iproduct.cc/join')
    // }},
    { label: '☕️ 联系/支持作者', type: 'normal', click: () => {
      shell.openExternal('https://www.iproduct.cc/support')
    }},
    { type: 'separator' },
    { label: '检查更新 '+app.getVersion(), type: 'normal', click: () => {
      check_updates()
    }},
    { type: 'separator' },
    { label: '退出', type: 'normal',accelerator: 'command+Q', click: () => app.quit() },
  ])

  tray.setContextMenu(contextMenu)
  // 使得左击也显示菜单
  tray.on('click', () => {
    tray.popUpContextMenu();
  });

})



// 注册快捷键
app.on('ready', async () => {
  // 注册快捷键 Alt+L
  globalShortcut.register('Alt+L', function () {
    Screenshot_beautification()
  });

  globalShortcut.register('Alt+A', function () {
    saveScreenshot();
  });

  globalShortcut.register('Alt+M', function () {
    add_outline();
  });
})





function Screenshot_beautification(){
  if (clipboard.availableFormats().includes('image/png') && clipboard.readImage() && clipboard.readImage().toDataURL()) {
    const image = clipboard.readImage()
    const savePath = path.join(__dirname, 'web', 'box.png');
    fs.writeFile(savePath, image.toPNG(), (err) => {
      if (err) throw err;
      
    });
    mainWindow = new BrowserWindow({
      backgroundColor: '#121212',
      width:1201,
      height:752,
      resizable: false, // 禁止调整边框大小
      titleBarStyle: 'hidden',
      titleBarOverlay: true,
      // icon: path.join(__dirname, 'build/icons', 'icon.icns'),
      webPreferences: {
        preload: path.resolve(__dirname, 'preload.js')
      }
    })   //设置打开的窗口小大
    mainWindow.loadFile('web/index.html')  //加载那个页面
    // mainWindow.webContents.openDevTools()
  } else {
    // const notification = new Notification({
    //   title: '当前剪切板不是图片内容',
    //   body: '请先截图后再使用吧',
    // });
    // notification.show();

    dialog.showMessageBoxSync({
      type: 'info',
      buttons: ['好的'],
      defaultId: 0, // 设置“确定”按钮为默认选中
      message: '当前剪切板不是图片内容',
      detail: '请先截图后再使用吧'
    })
  }
}


app.on('window-all-closed', function (event) {
  event.preventDefault()
})




ipcMain.on('set-title', (event, image_url) => {
  // const webContents = event.sender
  const clicktype = image_url[1];
  // 假设你的 base64 图片存储在变量 base64Image 中
  const base64Image = image_url[0];

  // 获取文件名和文件类型
  const matches = base64Image.match(/^data:(.+);base64,(.+)$/);
  const fileType = matches[1].split('/')[1];
  var image_path = new_time();
  const fileName = "iProduct" + image_path + ".png";
  // console.log("fileName"+fileName);

  // 生成文件保存的路径
  if (clicktype === "download") {
    const filePath = path.join(app.getPath('downloads'), fileName);
    // 将 base64 图片转换为 buffer
    const buffer = Buffer.from(matches[2], 'base64');
    // 将 buffer 写入文件
    fs.writeFile(filePath, buffer, (err) => {
      if (err) {
        const notification = new Notification({
          title: '下载失败',
          body: '图片保存失败，可联系开发者反馈',
        });
        notification.show();
      }else
      shell.openPath(path.join(app.getPath('downloads')))
    });
  }else if (clicktype === "copy") {
    const filePath = path.join(app.getPath('userData'), fileName);

    // 将 base64 图片转换为 buffer
    const buffer = Buffer.from(matches[2], 'base64');

    // 将 buffer 写入文件
    fs.writeFile(filePath, buffer, (err) => {
      if (err) {
        dialog.showMessageBoxSync({
          type: 'info',
          buttons: ['好的'],
          defaultId: 0, // 设置“确定”按钮为默认选中
          message: '复制失败',
          detail: '图片复制失败，可联系开发者反馈'
        })
      }
      

      // 读取图片文件的内容
      const imageContent = fs.readFileSync(filePath);
      // 将图片写入剪切板
      clipboard.writeImage(nativeImage.createFromBuffer(imageContent));

      copytoast();
    });
  }else if (clicktype === "screenshot") {
    const filePath = path.join(app.getPath('userData'), fileName);

    // 将 base64 图片转换为 buffer
    const buffer = Buffer.from(matches[2], 'base64');

    // 将 buffer 写入文件
    fs.writeFile(filePath, buffer, (err) => {
      if (err) {
        dialog.showMessageBoxSync({
          type: 'info',
          buttons: ['好的'],
          defaultId: 0, // 设置“确定”按钮为默认选中
          message: '复制失败',
          detail: '图片复制失败，可联系开发者反馈'
        })
      }
      

      // 读取图片文件的内容
      const imageContent = fs.readFileSync(filePath);
      // 将图片写入剪切板
      clipboard.writeImage(nativeImage.createFromBuffer(imageContent))
      Screenshot_beautification();
    });
  }else{
    dialog.showMessageBoxSync({
      type: 'info',
      buttons: ['好的'],
      defaultId: 0, // 设置“确定”按钮为默认选中
      message: '操作异常',
      detail: '联系开发者反馈'
    })
  }

})


// 获取当前日期和时间
function new_time(){
  let now = new Date();

  // 获取年、月、日、小时、分钟和秒
  let year = now.getFullYear();
  let month = now.getMonth() + 1;
  let day = now.getDate();
  let hour = now.getHours();
  let minute = now.getMinutes();
  let second = now.getSeconds();

  // 格式化输出
  let timetext = `${year}-${month}-${day} ${hour}.${minute}.${second}`;
  return timetext;
}


function check_updates(){
  const https = require('https');

  const options = {
    rejectUnauthorized: false
  };

  https.get('https://www.iproduct.cc/version.json', options, (res) => {
    let data = '';

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

    res.on('end', () => {
      const versionData = JSON.parse(data);
      const version = versionData.latest_version;

      if (version === app.getVersion()) {
        const notification = new Notification({
          title: '🚀 这已经是最新版本了哦',
          body: '不错，使用最新版本的人都是最美的',
        });
        notification.show();
      } else {
        dialog.showMessageBox({
          type: 'info',
          buttons: ['下载','稍后'],
          defaultId: 0, // 设置“确定”按钮为默认选中
          message: '🚲 发现新版本',
          detail: '有新版本'+version+'可以更新'
        }).then(response => {
          if (response.response === 0) { // 如果用户点击“确定”
            shell.openExternal(versionData.url)
          }
        });
        
      }
    });
  }).on('error', (error) => {
    console.error(error);
  });
}


function auto_check_updates(){
  const https = require('https');

  const options = {
    rejectUnauthorized: false
  };

  https.get('https://www.iproduct.cc/version.json', options, (res) => {
    let data = '';

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

    res.on('end', () => {
      const versionData = JSON.parse(data);
      const version = versionData.latest_version;

      if (version === app.getVersion()) {
        // console.log('最新版本');
      } else {
        dialog.showMessageBox({
          type: 'info',
          buttons: ['下载','稍后'],
          defaultId: 0, // 设置“确定”按钮为默认选中
          message: '🚲 发现新版本',
          detail: '有新版本'+version+'可以更新'
        }).then(response => {
          if (response.response === 0) { // 如果用户点击“确定”
            shell.openExternal(versionData.url)
          }
        });
      }
    });
  }).on('error', (error) => {
    console.error(error);
  });
}




function welcome(){
  const filePath = path.join(__dirname, 'setting.json');

  if (fs.existsSync(filePath)) {
    // console.log(2);
  } else {
    fs.writeFileSync(filePath, '{"firstTime": true}');
    mainWindow = new BrowserWindow({
      width:800,
      height:500,
      resizable: false, // 禁止调整边框大小
      titleBarStyle: 'hidden',
      titleBarOverlay: true
    })   //设置打开的窗口小大
    mainWindow.loadFile('web/welcome.html')  //加载那个页面
    mainWindow.once('ready-to-show', () => {
      mainWindow.show(); // 当页面准备就绪时展示窗口
    });
  }
}

// 截图操作，保存到本地图片，并展示图片
function saveScreenshot() {
  let screenshotPath = path.join(app.getAppPath(), "screenshot.png");

  screenshot(screenshotPath, function(error, complete) {
    if(error) {
      console.log(error);
    } else {
      showWindow();
    }
  });
}

// 截图剪裁页面
function showWindow() {
  let { width, height } = screen.getPrimaryDisplay().bounds;
  mainWindow = new BrowserWindow({
      fullscreen: undefined,
      width,
      height,
      x: 0,
      y: 0,
      transparent: true,
      frame: false,
      skipTaskbar: true,
      autoHideMenuBar: true,
      movable: false,
      resizable: false,
      enableLargerThanScreen: true,
      hasShadow: false,
      webPreferences: {
          nodeIntegration: true,
          preload: path.resolve(__dirname, 'preload.js')
      }
  });

  mainWindow.loadFile('screenshot.html');
}

// 加个描边
function add_outline(){
  let image = clipboard.readImage();
  if (!image.isEmpty()) {
    // 将图片转换为 Buffer
    const imageBuffer = image.toPNG();
    // 使用 sharp 添加边框
    sharp(imageBuffer)
      .extend({ top: 1, bottom: 1, left: 1, right: 1, background: { r: 0, g: 0, b: 0, alpha: 0.3 } })
      .toBuffer()
      .then((outputBuffer) => {
        // 将带边框的图像数据写回剪贴板
        clipboard.writeImage(nativeImage.createFromBuffer(outputBuffer));
      });
      copytoast();
  } else {
    dialog.showMessageBoxSync({
      type: 'info',
      buttons: ['好的'],
      defaultId: 0, // 设置“确定”按钮为默认选中
      message: '当前剪切板不是图片内容',
      detail: '请先截图后再使用吧'
    })
  }
}

function copytoast(){
  const { width: screenWidth } = screen.getPrimaryDisplay().workAreaSize;

  mainWindow = new BrowserWindow({
    width: 138,
    height: 68,
    x: Math.round((screenWidth - 138) / 2),
    y: 80,
    transparent: true,
    frame: false,
    skipTaskbar: true,
    autoHideMenuBar: true,
    movable: false,
    resizable: false,
    enableLargerThanScreen: true,
    hasShadow: false,
    webPreferences: {
        nodeIntegration: true,
    }
  });

  mainWindow.loadFile('copytoast.html');
}