import { LoginOptions, RegisterOptions, ShareOptions, UxWxworkFail, UxWxworkSuccess } from '../../interface.uts'
import { MyFailImpl } from '../../unierror';

import Util from './Util.uts';
import Bitmap from "android.graphics.Bitmap";

import WWAPIFactory from "com.tencent.wework.api.WWAPIFactory";
import IWWAPI from "com.tencent.wework.api.IWWAPI";
import WWAuthMessage from "com.tencent.wework.api.model.WWAuthMessage";
import BaseMessage from "com.tencent.wework.api.model.BaseMessage";
import IWWAPIEventHandler from "com.tencent.wework.api.IWWAPIEventHandler";
import WWMediaText from "com.tencent.wework.api.model.WWMediaText";
import WWMediaImage from "com.tencent.wework.api.model.WWMediaImage";
import WWMediaVideo from "com.tencent.wework.api.model.WWMediaVideo";
import WWMediaLink from "com.tencent.wework.api.model.WWMediaLink";
import WWMediaFile from "com.tencent.wework.api.model.WWMediaFile";
import WWMediaMiniProgram from "com.tencent.wework.api.model.WWMediaMiniProgram";

let appid = ''
let agentid = ''
let schema = ''
let appName = ''

export class Weixin {

	api : IWWAPI | null = null

	/**
	 * 注册
	 */
	register(options : RegisterOptions) {
		appid = options.appid
		agentid = options.agentid
		schema = options.schema
		appName = Util.getPackageName()

		if (appid == '' || agentid == '' || schema == '') {
			options.fail?.(new MyFailImpl(9010001))
			return
		}
		
		this.api = WWAPIFactory.createWWAPI(UTSAndroid.getAppContext()!)
		let b = this.api?.registerApp(options.schema) ?? false
		
		if(b) {
			options.success?.({
				code: '0',
				msg: 'register success'
			} as UxWxworkSuccess)
		} else {
			options.fail?.(new MyFailImpl(9010001))
		}
	}

	/**
	 * 是否注册
	 */
	isRegister(fail ?: (res : UxWxworkFail) => void): boolean {
		
		if(this.api == null) {
			fail?.(new MyFailImpl(9010000))
			return false
		} else {
			
			if(!this.isInstalled()) {
				fail?.(new MyFailImpl(9010007))
				return false
			}
			
			return true
		}
	}

	/**
	 * 登录
	 */
	login(options : LoginOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}
		
		let req = new WWAuthMessage.Req();
		req.sch = schema;
		req.appId = appid;
		req.agentId = agentid;
		
		class WAPIEventHandler extends IWWAPIEventHandler {
			
			override handleResp(resp: BaseMessage) {
				if (resp instanceof WWAuthMessage.Resp) {
					let rsp = resp as WWAuthMessage.Resp;
					if (rsp.errCode == WWAuthMessage.ERR_CANCEL) {
						// 登录取消
						options.fail?.(new MyFailImpl(9010005))
					}else if (rsp.errCode == WWAuthMessage.ERR_FAIL) {
						// 登录失败
						options.fail?.(new MyFailImpl(9010004))
					} else if (rsp.errCode == WWAuthMessage.ERR_OK) {
						// 登录成功
						options.success?.({
							code: rsp.code,
							msg: 'auth success'
						} as UxWxworkSuccess)
					}
				}
			}
		}
		
		let b = this.api?.sendMessage(req, new WAPIEventHandler()) ?? false
		
		if(!b) {
			options.fail?.(new MyFailImpl(9010003))
		}
	}

	/**
	 * 分享
	 */
	share(options : ShareOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}
		
		switch (options.type) {
			case 0:
				this.shareWebpage(options)
				break;
			case 1:
				this.shareText(options)
				break;
			case 2:
				this.shareImage(options)
				break;
			case 3:
				this.shareFile(options)
				break;
			case 4:
				this.shareVideo(options)
				break;
			case 5:
				this.shareMp(options)
				break;
		}
	}

	/**
	 * 图文
	 */
	private shareWebpage(options : ShareOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}

		let req = new WWMediaLink();
		req.webpageUrl = options.href ?? ''
		req.title = options.title ?? ''
		req.description = options.summary ?? ''
		
		req.appPkg = UTSAndroid.getAppContext()!.getPackageName();
		req.appName = appName;
		req.appId = appid;
		req.agentId = agentid;
		
		Util.getPath(options.imageUrl, 100, 100, (path : string | null) => {
			req.thumbUrl = path ?? ''
			
			let b = this.api?.sendMessage(req) ?? false
			if(!b) {
				options.fail?.(new MyFailImpl(9010002))
			}
		})
	}

	/**
	 * 纯文本
	 */
	private shareText(options : ShareOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}

		let req = new WWMediaText();
		req.text = options.title ?? '';

		req.appPkg = UTSAndroid.getAppContext()!.getPackageName();
		req.appName = appName;
		req.appId = appid;
		req.agentId = agentid;

		let b = this.api?.sendMessage(req) ?? false
		if(!b) {
			options.fail?.(new MyFailImpl(9010002))
		}
	}

	/**
	 * 纯图片
	 */
	private shareImage(options : ShareOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}

		let req = new WWMediaImage();
		
		req.appPkg = UTSAndroid.getAppContext()!.getPackageName();
		req.appName = appName;
		req.appId = appid;
		req.agentId = agentid;

		Util.getPath(options.imageUrl, 0, 0, (path : string | null) => {
			console.log(path);
			req.fileName = "img";
			req.filePath = path ?? ''
			
			let b = this.api?.sendMessage(req) ?? false
			if(!b) {
				options.fail?.(new MyFailImpl(9010002))
			}
		})
	}

	/**
	 * 视频
	 */
	private shareVideo(options : ShareOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}

		let req = new WWMediaVideo();
		
		req.appPkg = UTSAndroid.getAppContext()!.getPackageName();
		req.appName = appName;
		req.appId = appid;
		req.agentId = agentid;

		req.fileName = "video";
		req.filePath = options.mediaUrl ?? ''
		
		let b = this.api?.sendMessage(req) ?? false
		if(!b) {
			options.fail?.(new MyFailImpl(9010002))
		}
	}

	/**
	 * 文件
	 */
	private shareFile(options : ShareOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}
		
		let req = new WWMediaFile();
		
		req.appPkg = UTSAndroid.getAppContext()!.getPackageName();
		req.appName = appName;
		req.appId = appid;
		req.agentId = agentid;

		req.fileName = "file";
		req.filePath = options.filePath ?? '';
		
		let b = this.api?.sendMessage(req) ?? false
		if(!b) {
			options.fail?.(new MyFailImpl(9010002))
		}
	}

	/**
	 * 小程序
	 */
	private shareMp(options : ShareOptions) {
		if(!this.isRegister(options.fail)) {
			return
		}
		
		if (options.miniProgram == null) {
			return
		}

		let req = new WWMediaMiniProgram();
		
		req.appPkg = UTSAndroid.getAppContext()!.getPackageName();
		req.appName = appName;
		req.appId = appid;
		req.agentId = agentid;
		req.schema = schema;
		
		req.webpageUrl = options.miniProgram!.webUrl ?? ''

		// 正式版:0，测试版:1，体验版:2
		if (options.miniProgram!.type == 0) {
			req.miniProgramType = WWMediaMiniProgram.MiniProgramTypeRelease;
		} else if (options.miniProgram!.type == 1) {
			req.miniProgramType = WWMediaMiniProgram.MiniProgramTypeTest;
		} else if (options.miniProgram!.type == 2) {
			req.miniProgramType = WWMediaMiniProgram.MiniProgramTypePreview;
		}

		req.username = options.miniProgram!.id + '@app'
		req.path = options.miniProgram!.path
		
		req.title = options.title ?? ''
		req.description = options.summary ?? ''
		
		Util.getBitmap(options.imageUrl, 500, 400, (bitmap : Bitmap | null, bytes : ByteArray | null) => {
			bitmap?.recycle()

			if (bytes != null) {
				req.hdImageData = bytes
			}
			
			let b = this.api?.sendMessage(req) ?? false
			if(!b) {
				options.fail?.(new MyFailImpl(9010002))
			}
		})
	}

	/**
	 * 企业微信app是否安装
	 */
	isInstalled() : boolean {
		if(this.api == null) {
			return false
		}
		
		return this.api!.isWWAppInstalled()
	}

	/**
	 * 打开企业微信app
	 */
	openApp() {
		if(this.api == null) {
			return
		}
		
		this.api?.openWWApp()
	}
}
