PARAMETERS cBdd

ON ERROR DO errhand 
PUBLIC o, conexion
conexion = CREATEOBJECT( "MSXML2.ServerXMLHTTP" )
o = CREATEOBJECT ('gs_class',cBdd)

DEFINE CLASS gs_class AS CUSTOM 

nConn    = -1
cBdd     = 'fss1'
cHost    = 'localhost'
cSeccion = 'g1191724778001'
cDir         = '/temp'

cbEnterprise = ''
cbRUC 	     = ''

cWebResult   = ''

ncrono = 0

FUNCTION init (cBdd)
	this.cBdd = IIF (EMPTY(cBdd),'fss1',cBdd)

	this.nConn = SQLCONNECT('fss1')

	this.sqlexec('USE '+this.cBdd)
	
	this.cbEnterprise = this.setup('cbEnterprise')
	this.cbRUC 	      = this.setup('cbRUC')
	this.cHost 		  = this.newSetup ('gs_host','http://www.pedidosec.com')

	this.cDir = '/temp/'+this.cbRUC
	IF !DIRECTORY(this.cDir)
		MKDIR (this.cDir)
	ENDIF
ENDFUNC



FUNCTION execMySqlScript(cSql)
	WAIT WINDOW 'Aplicando cambios...' NOWAIT 
	
	cPuertoext  = this.setup("cPuertoext")
	cDBPassword = this.setup('cDBPassword')
	cPuertoext  = IIF(!EMPTY(cPuertoext),' --port=','')+cPuertoext
	cDBPassword = IIF(!EMPTY(cDBPassword),' --password=','')+cDBPassword
	
	this.sqlexec("show variables where variable_name = 'basedir'",'curBin')
	cPathBin = ALLTRIM(STRTRAN(curBin.value,CHR(0),''))+'\bin\'
	

	STRTOFILE(cSql,'temp\pa.sql')
	cmd = cPathBin+'mysql.exe < temp\pa.sql -u root ' + cPuertoExt + cDBPassword
	RUN &cmd
	
	WAIT WINDOW 'Ok' TIMEOUT 1
ENDFUNC


FUNCTION sqlexec(cCad,cCursor)
	IF SQLEXEC(this.nConn,cCad,IIF(EMPTY(cCursor),'sqlresult',cCursor),aInfo)<0
		DO errhand
	ENDIF

	RETURN aInfo[2]
ENDFUNC


FUNCTION closeDB
	IF This.nConn>0
		SQLDISCONNECT(This.nConn)
	ENDIF
ENDFUNC

FUNCTION runLink(cHttp, cResult)
	cResult = this.runUrl(cHttp) 
	RETURN cResult != '@@'
ENDFUNC

FUNCTION runUrl
	PARAMETERS url, cData, cMetodo

	LOCAL lcHTML,lnText,lRet, iCount


	IF EMPTY(cMetodo)
		cMetodo = 'GET'
	ENDIF
	
	lConn = ""

	TRY
		conexion.open(cMetodo, url, .F.)
		lResolve =  5 * 1000
		lConnect =  5 * 1000
		lSend    = 120 * 1000
		lReceive = 120 * 1000
		conexion.setTimeouts(lResolve, lConnect, lSend, lReceive)

		IF EMPTY(cData)
			cData = null
		ENDIF

		conexion.send(cData)

		IF conexion.status = 200 THEN
			cResult = conexion.responseText
		ELSE
			cResult = '@@'+TRANSFORM(conexion.status)
		ENDIF
	CATCH TO lConn
	ENDTRY
	lConn = TRANSFORM(lConn)
	IF !EMPTY(lConn)
		cResult = '@@'+lConn
	ENDIF

	This.cWebResult = cResult
	
	RETURN cResult
ENDFUNC


FUNCTION setup
PARAMETERS _llave
LOCAL cValue
	cValue = ''
	IF this.sqlexec('select value from setup where id=?_llave','curSetup')>0
		cValue = ALLTRIM(curSetup.value)
	ENDIF
	RETURN cValue
ENDFUNC

FUNCTION setSetup
PARAMETERS _llave,_valor
	
	this.sqlexec('UPDATE setup SET value=?_valor where id = ?_llave')

ENDFUNC

FUNCTION newSetup
PARAMETERS _llave,_valor
	
	cValue = _valor
	IF this.sqlexec('select value from setup where id=?_llave','curSetup')=0
		this.sqlexec('INSERT INTO setup (id,type,value) VALUES (?_llave,"C",?_valor)')
	ELSE
		cValue = ALLTRIM(curSetup.value)
	ENDIF
	RETURN cValue

ENDFUNC


FUNCTION crono
LPARAMETERS nOp, lBox

	LOCAL nCrono, nHor, nMin, nSeg , lcOut

	IF nOp=0
		this.ncrono = SECONDS()
	ENDIF

	lcOut = ''

	IF nOp=9
		nCrono = SECONDS()-this.nCrono
		this.nCrono = 0
		
		nHor = ALLTRIM(PADL(INT(nCrono/3600),8))+' horas '
		nMin = ALLTRIM(PADL(INT(MOD(nCrono/60,60)),3))+' min. '
		nSeg = ALLTRIM(PADL(INT(MOD(nCrono,60)),3))+' seg. ' 
		
		lcOut = nHor+nMin+nSeg 
		IF !EMPTY(lBox)
			IF lBox = 1
				WAIT WINDOW lcOut nowait
			ELSE
				MESSAGEBOX(lcOut,64,'Ghost')
			ENDIF
		ENDIF
		
	ENDIF
	RETURN lcOut
ENDFUNC

FUNCTION explode
	LPARAM cCad, aRet, cCharType

	LOCAL ss, nLen, lExit

	IF EMPTY(cCharType)
		cCharType = ' '
	ENDIF

	DIMENSION aRet [1]
	nLen = 0
	lExit = .f.
	IF !EMPTY(cCad)
		DO WHILE !lExit
			pos = AT(cCharType, cCad)
			IF pos > 0
				ss   = allt(SUBSTR(cCad,1,pos-1))
				cCad = allt(SUBSTR(cCad,pos+1))
			ELSE
				ss   = cCad
				lExit = .t.
			ENDIF
			nLen = nLen +1
			DIMENSION aRet [nLen]
			aRet [nLen] = ss
		ENDDO
	ENDIF
	RETURN nLen
ENDFUNC

PROCEDURE CreaZip
PARAMETERS cNombre     
PRIVATE lRetorno
  lRetorno = .f.
  nHandle = fCreate(cNombre)
  If nHandle > 0
    fWrite(nHandle,"PK"+Chr(5)+Chr(6)+Replicate(Chr(0),18),22)
    fClose(nHandle)    
    lRetorno = .t.
  EndIf
RETURN lRetorno

PROCEDURE Zip
PARAMETERS cFileName
PRIVATE oShell,oFolder
 
  cArchivoZip =this.getFileName(cFileName,'.ZIP')
  cFileName=this.getFileName(cFileName)
  
  If File(cArchivoZip)
    Delete File (cArchivoZip) RECYCLE
  EndIf

  If THIS.CreaZip(cArchivoZip)
	  oShell = CREATEOBJECT("Shell.Application")
	  oFolder = oShell.NameSpace(cArchivoZip)

	  If IsNull(oFolder)
	    =MessageBox("No se puede abrir el zip.",48,"Advertencia:")
	  ELSE
	    oFolder.CopyHere(cFileName)
	  ENDIF
  ENDIF
  Release oShell,oFolder
ENDPROC


FUNCTION getFileName(cFileName,cExt)
	cFileName = LOCFILE(cFileName)
	IF EMPTY(cExt)
		cExt = '.'+JUSTEXT(cFileName)
	ENDIF
	RETURN ADDBS(JUSTPATH(cFileName))+JUSTSTEM(cFileName)+cExt
ENDFUNC


PROCEDURE jsonparse
PARAMETERS pcJSON, poTarget
LOCAL lcScript
LOCAL sc AS scriptcontrol
IF PCOUNT() = 1
	poTarget = NEWOBJECT("Empty")
ENDIF

sc = CREATEOBJECT("scriptcontrol")
sc.Language="JScript"
TEXT TO lcScript TEXTMERGE NOSHOW
	function parseJSON() {
	  var json = << pcJSON >>;
	  var str = "";
	  for (var name in json) {
	    var realType = RealTypeOf(json[name]);
	    if ( realType == "array" ) {
	      str += "ADDPROPERTY(poTarget,'"+name+"(1)',.f.)\r\n";
	      for (var i = 0;i < json[name].length;i++) {
	        var arrayElement = "poTarget."+name+"["+(i+1)+"]"
	        str += "DIMENSION "+arrayElement+"\r\n";
	        var value = json[name][i];
		    var realType = RealTypeOf(value);
	        if ( realType == "object") {
	          str += arrayElement + " =  oApp.jsonParse(\""+toJson(value)+"\")\r\n";
	        } else if ( realType == "string" ) {
	          str += arrayElement + ' = "'+value+'"'+"\r\n";
	        } else if ( realType == "number" ) {
	          str += arrayElement + " = "+value+"\r\n";
	        } else if ( realType == "date" ) {
	          str += arrayElement + " = {"+value+"}\r\n";
	        } else if ( realType == "boolean" ) {
		      str += arrayElement + " = "+((value)?".t.":".f.")+"\r\n";
            }
          }
        } else if ( realType == "string" ) {
	      str += "ADDPROPERTY(poTarget,'"+name+"',["+json[name]+"])\r\n";
	    } else if ( realType == "number" ) {
	      str += "ADDPROPERTY(poTarget,'"+name+"',"+json[name]+")\r\n";
	    } else if ( realType == "date" ) {
	      str += "ADDPROPERTY(poTarget,'"+name+"',{"+json[name]+"})\r\n";
	    } else if (realType == "boolean" ) {
	      str += "ADDPROPERTY(poTarget,'"+name+"',"+((json[name])?".t.":".f.")+")\r\n";
        } else if ( realType == "object") {
	      str += "ADDPROPERTY(poTarget,'"+name+"',oApp.jsonParse(\""+toJson(json[name])+"\"))\r\n";
        }
      }
	  return str;
    }

	function RealTypeOf(v) {
          if (typeof(v) == "object") {
            if (v == null) return "null";
            if (v.constructor == (new Array).constructor) return "array";
            if (v.constructor == (new Date).constructor) return "date";
            if (v.constructor == (new RegExp).constructor) return "regex";
            return "object";
          }
          return typeof(v);
        }

        function toJson(obj) {
          switch (typeof obj) {
            case 'object':
              if (obj) {
                  var list = [];
                  if (obj instanceof Array) {
                       for (var i=0;i < obj.length;i++) {
                             list.push(toJson(obj[i]));
                       }
                       return '[' + list.join(',') + ']';
                  } else {
                       for (var prop in obj) {
                             list.push(prop + ':' + toJson(obj[prop]));
                       }
                       return '{' + list.join(',') + '}';
                  }
              } else {
                  return 'null';
              }
            case 'string':
              return "'" + obj.replace(/(['])/g, '\\$1') + "'";
            case 'number':
            case 'boolean':
              return new String(obj);
          }
        }
ENDTEXT
sc.AddCode(lcScript)
lcScript = sc.Eval("parseJSON();")
EXECSCRIPT(lcScript)
sc = null
RELEASE sc

RETURN poTarget


ENDPROC

ENDDEFINE


PROCEDURE errhand
	=AERROR(aErrorArray)  
  	
  	cErr = ''
  	FOR __n__= 1 TO 7
  		IF !ISNULL(aErrorArray(__n__))
	      	cErr = cErr +  TRANSFORM(aErrorArray(__n__))+CHR(13)
	    ENDIF
	    
   	ENDFOR
	   	
   MESSAGEBOX(cErr+CHR(13)+MESSAGE(1),63,'Ghost-Errores')
  * CLEAR EVENTS
  * cancel
ENDPROC
