import Cursor from 'android.database.Cursor';
import SQLiteDatabase from 'android.database.sqlite.SQLiteDatabase';
import SQLiteOpenHelper from 'android.database.sqlite.SQLiteOpenHelper';
import Environment from 'android.os.Environment';

import { createSQLiteContextOptions, executeSqlOptions, selectSqlOptions, executeSqlOptionsResult, selectSqlOptionsResult, CreateSQLiteContext, transactionOptions, transactionResult, ICreateSQLiteContextError } from '../interface.uts';
//import { createSQLiteContextOptions, executeSqlOptions, selectSqlOptions, transactionOptions } from '../interface.uts';
import { createSQLiteContextFailImpl } from '../unierror.uts';

class SQLiteContext extends SQLiteOpenHelper {
  private dbName: string | null;
  
  constructor(name: string) {
    console.log(UTSAndroid.getResourcePath("/static/db/"+name))	
	super(UTSAndroid.getAppContext(), UTSAndroid.getResourcePath("/static/db/"+name), null, 1);
	this.dbName = name;
  }
  
    
  override onCreate(db: SQLiteDatabase):void {
	  
  }
  
  override onUpgrade(db: SQLiteDatabase, oldVersion:Int, newVersion:Int):void {
  	 
  }

  public executeSql(options: executeSqlOptions) {
    const database: SQLiteDatabase = this.getWritableDatabase();
    const SqlArray = options.sql.split(';');
    let result: executeSqlOptionsResult = {
		data: [] as boolean[],
		errMsg: 'ok'
	}
		
    try {
      for (let i = 0; i < SqlArray.length; i++) {
        if (SqlArray[i].length > 0) {
          const sql = SqlArray[i].replace(/^\s+/, '');
          try {
            database.execSQL(sql);
            result.data.push(true);
          } catch(e:Error) {
            result.data.push(false);
          }
        }
      }
      options.success?.(result);
    } catch (e) {      
      const err = new createSQLiteContextFailImpl(1000002);
      result.errMsg = err.errMsg;
      options.fail?.(result);
    }
    options.complete?.(result);
    return result;
  }

  public selectSql(options: selectSqlOptions) {
    const database: SQLiteDatabase = this.getReadableDatabase();
    const SqlArray = options.sql.split(';');
    let result: selectSqlOptionsResult = {
		data: [] as UTSJSONObject[],
		errMsg: 'ok',		
	}
		
    try {
      for (let i = 0; i < SqlArray.length; i++) {
        if (SqlArray[i].length > 0) {
          const sql = SqlArray[i].replace(/^\s+/, '');
          try {
            const cursor: Cursor = database.rawQuery(sql, null);
            //获取查询结果的字符串并push到result.data中
            if (cursor.moveToFirst()) {
              do {
                const row = cursor.getColumnCount();
                const utsJsonObject = {} as UTSJSONObject;
                for (let j:Int = 0; j < row; j++) {
                  //rowArray.push(cursor.getString(j)!=null? cursor.getString(j):'');
				  //let obj = {cursor.getColumnName(j):cursor.getString(j)!=null? cursor.getString(j):''}
				  //rowArray.push(obj)
				  utsJsonObject.set(cursor.getColumnName(j).toString(), cursor.getString(j)!=null? cursor.getString(j):'')
                }
                result.data.push(utsJsonObject);
              } while (cursor.moveToNext());
            }
            cursor.close();
          } catch(e:Error) {
			console.log(e)			
            result.data.push({});
          }
        }
      }
      options.success?.(result);
    } catch (e) {      
      const err = new createSQLiteContextFailImpl(1000003);
      result.errMsg = err.errMsg;
      options.fail?.(result);
    }
    options.complete?.(result);
    return result;
  }
  /*
  public close(){
	  const database: SQLiteDatabase = this.getReadableDatabase();
	  database.close();
  } */

  public transaction(options: transactionOptions) {
    const database: SQLiteDatabase = this.getReadableDatabase();
    const transaction = options.operation;
    let result: transactionResult = {
		errMsg: 'transaction:ok',
	}
    try {
      if (transaction == 'begin') {
        //开启事务
        database.execSQL('BEGIN TRANSACTION');
      } else if (transaction == 'commit') {
        //提交事务
        database.execSQL('COMMIT');
      } else if (transaction == 'rollback') {
        //回滚事务
        database.execSQL('ROLLBACK');
      }
      options.success?.(result);
    } catch (e) {
      let errCode = 1000008;
      if (transaction == 'begin') {
        errCode = 1000004;
      } else if (transaction == 'commit') {
        errCode = 1000005;
      } else if (transaction == 'rollback') {
        errCode = 1000006;
      }
      const err = new createSQLiteContextFailImpl(errCode);
	  const errInfo = {errMsg:err.errMsg } as  transactionResult ;	
      options.fail?.(errInfo);
    }    
	let ret = {		
		errMsg: result.errMsg as string
	} as UTSJSONObject
	options.complete?.(result);
    return ret;
  }
}

export const createSQLiteContext = function (dbName: string): SQLiteContext {
  const name = dbName + '.db';
  return new SQLiteContext(name);
}

