package com.skysidestudio.skyside3gbyEditor;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;



import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;

import java.text.SimpleDateFormat;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class Public {
	
	public static String DIRPATH = Environment.getExternalStorageDirectory().getPath() + "/skyside3gby3";
	public static String SDPATH = Environment.getExternalStorageDirectory().getPath() + "/skyside3gby3/";

	

	public static Config picStyle = Bitmap.Config.ARGB_8888;//图像制式
	public static boolean picCycle = false;
	//main
	
	public static int flag=0;
	
	public static int KeyCodeFlag=0;
	public static int KeyInvalidateFlag=1;
	
	public static int state=0;
	public static final int KeyReturn=8;
	public static final int KeyLeft0=1;
	public static final int KeyRight0=2;
	public static final int KeyUp0=3;
	public static final int KeyDown0=4;
	public static final int KeyEsc=5;
	public static final int KeySpace=6;
	public static final int KeyHome=7;
	public static final int ENDL=-30317;
	public static final int SPACE=-30521;
	public static final int OUTDATA=-30001;
	public static final int ARRAYMAX=65535;
	public static final int TEXTMAX=1000;
	
	public static final int HEROMAX=200;
	public static final int CITYMAX=38;
	public static final int GOODMAX=33;
	
	public static final int DSTINVERT=-1;
	public static final int SRCCOPY=1;
	public static final int SRCAND=2;
	public static final int SRCPAINT=3;
	public static final int TILE=9;
	//public static final int SPR=-1;

	
	public static String [][]storetext=new String[22][TEXTMAX];
	public static String []texta=new String[TEXTMAX];
	
	public static int id=0;//用于管理infile的值，配合numarray使用
	public static int [][]storenumarray=new int[39][ARRAYMAX];
	public static int []numarray=new int[ARRAYMAX];


	public static String []textb=new String[TEXTMAX];//用于技能存储

	public static int tempvar=0;
	
	public static String[] filename_existed=new String[22];
	public static int filename_current_max=0;
	public static int[] filename_existed_maxlen= new int[22];
	
	public static String[] sdtfilename_existed=new String[39];
	public static int sdtfilename_current_max=0;
	public static int[] sdtfilename_existed_maxlen= new int[39];
	
	public static int arg0=0;
	public static int arg1=0;
	public static int arg2=0;
	public static int arg3=0;



	/***********************************************************************
	 * 说明:    获取文本函数
	 * 输入参数: char *filename——文件名称
	 * 返回值  : 无
	 * 功能	   : 获取文本内容
	 * 修改历史:
	 *               姓名            日期             说明
	 *             ------          ----------      -------------
	 *             吴亭杰          2012-10-5       完成基本功能
	***********************************************************************/
	public static int outtextfinish(String filename)
	{

		File path = new File(DIRPATH);
		if (!path.exists()) 
		{
			path.mkdirs();	
		}
		File sdfilename = new File(SDPATH +filename);

		//sd卡中读取
		//Log.v("fileout",SDPATH +filename+"   "+id);
		try
		{

			FileOutputStream fout = new FileOutputStream(sdfilename);

			for(int i=0;i<id;i++)
			{
				fout.write(texta[i].getBytes("GB2312"));   
				//Log.v("fileout1",texta[i]);
			}
			fout.close();
			//Log.v("fileout2",id+"");
			return id;
		}
		catch(Exception e){
			//Log.v("fileout3",texta[id-1]);
			e.printStackTrace();
		}



		return 0;

	}
	

	public static int infileget()
	{
		id++;
		//Log.v("tiles",id+"");
		//if(id>tempvar)return OUTDATA;
		return numarray[id-1];
	}
	
	public static int saveinfileinit(String filename)
	{
		File path = new File(DIRPATH);
        if (!path.exists()) 
        {
        	path.mkdirs();	
        }
        
		File sdfilename = new File(SDPATH +filename);
		
		//Context context=ContextUtil.getInstance();
		Log.v("hihi",filename);
		id=0;
		tempvar=0;
		try {
			   
	        FileInputStream inStream= new FileInputStream(sdfilename);
	        ByteArrayOutputStream stream=new ByteArrayOutputStream();
	        byte[] buffer=new byte[1024];
	        int length=-1;

	        while((length=inStream.read(buffer))!=-1)   {
	            stream.write(buffer,0,length);
	        }

	        stream.close();
	        inStream.close();
	        String[] ary=stream.toString().split(" |\r\n");
	        for(int i=0;i<numarray.length;i++)
			{
	        	numarray[i]=OUTDATA;	
			}
	        for(int i=0;i<ary.length;i++)
			{
	        	numarray[i]=Integer.parseInt(ary[i]);	
			}
	        tempvar=ary.length;
	        return ary.length;
	        
	    } 
		catch (FileNotFoundException e) {
	        e.printStackTrace();
	    }
	    catch (IOException e){
	        return -1;
	    }
		
		
		return 0;
	}
	
	public static int saveinfileget()
	{
		id++;
		if(id>tempvar)return OUTDATA;
		return numarray[id-1];
	}
	
	
	public static void outfileget(int innum)
	{
		numarray[id]=innum;
		id++;
	}
	
	public static void outfileget(String instr)
	{
		if(instr==" ")numarray[id]=SPACE;
		if(instr=="\n")numarray[id]=ENDL;
		id++;
	}
	
	public static void outtextget(String instr)
	{
		texta[id]=instr;
		id++;
	}
	
	public static int outfilefinish(String filename)
	{
		File sdfilename = new File(SDPATH +filename);
		//Log.v("sdfilename",""+sdfilename);
		try {
            FileOutputStream outStream=new FileOutputStream(sdfilename);
            //Log.v("id",id+"");
            for(int i=0;i<id;i++)
			{
            	//Log.v("numarray",numarray[i]+"");
//            	if(i<10)Log.v("hj2",numarray[i]+"");
            	if(numarray[i]==ENDL)
            	{
            		//outStream.write("\r\n".getBytes());
            		
            	}
            	else if(numarray[i]==SPACE)
            	{
            		outStream.write(" ".getBytes());
            		
            	}
            	else
            	{
            		
            		outStream.write((numarray[i]+"").getBytes());
            	}
			}
            
            outStream.close();
        } catch (FileNotFoundException e) {
            return -1;
        }
        catch (IOException e){ 
            return -1;
        }
		
		return 0;
	}
	
	public static String getListText(int no)
	{

		
		return "";
	}

	public static String filterCode(String string)
	{
        if (string != null) {
            string = string.trim();
            byte[] zero = new byte[1];
            zero[0] = (byte) 0;
            String s = new String(zero);
            string = string.replace(s, "");
        }
        return string;
    }





	public static String getMethodName()
	{
		StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
		StackTraceElement e = stacktrace[3];
		String methodName = e.getMethodName();
		String fileName = e.getFileName();
		return fileName + "::" + methodName;
	}

	public static void DeleteLog()
	{
		File path = new File(SDPATH + "Log/");
		if (!path.exists())
		{
			path.mkdirs();
		}
		SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
		String t = format1.format(new java.util.Date());
		File sdfilename = new File(SDPATH + "Log/" + t + ".log");
		if (sdfilename.exists())
		{
			sdfilename.delete();
		}

		return;

	}

	/**
	 * 通过ftp上传文件
	 *
	 * @param url
	 *            ftp服务器地址 如： 192.168.1.110
	 * @param port
	 *            端口如 ： 21
	 * @param username
	 *            登录名
	 * @param password
	 *            密码
	 * @param remotePath
	 *            上到ftp服务器的磁盘路径
	 * @param fileNamePath
	 *            要上传的文件路径
	 * @param fileName
	 *            要上传的文件名
	 * @return
	 */
	public static String ftpUpload(String url, String port, String username,
								   String password, String remotePath, String fileNamePath,
								   String fileName)
	{
		FTPClient ftpClient = new FTPClient();
		FileInputStream fis = null;
		String returnMessage = "0";
		try
		{
			ftpClient.connect(url, Integer.parseInt(port));
			boolean loginResult = ftpClient.login(username, password);
			int returnCode = ftpClient.getReplyCode();
			if (loginResult && FTPReply.isPositiveCompletion(returnCode))
			{// 如果登录成功
				ftpClient.makeDirectory(remotePath);
				// 设置上传目录
				ftpClient.changeWorkingDirectory(remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				// ftpClient.setControlEncoding("UTF-8");
				ftpClient.enterLocalPassiveMode();
				fis = new FileInputStream(fileNamePath + fileName);
				ftpClient.storeFile(fileName, fis);

				returnMessage = "1"; // 上传成功
			} else
			{// 如果登录失败
				returnMessage = "0";
			}

		} catch (IOException e)
		{
			e.printStackTrace();
			throw new RuntimeException("FTP客户端出错！", e);
		} finally
		{
			// IOUtils.closeQuietly(fis);
			try
			{
				ftpClient.disconnect();
			} catch (IOException e)
			{
				e.printStackTrace();
				throw new RuntimeException("关闭FTP连接发生异常！", e);
			}
		}
		return returnMessage;
	}



	public static void copyIniToSD(String filename) throws IOException
	{
		InputStream myInput;
		java.io.OutputStream myOutput = new FileOutputStream(Public.SDPATH + filename);
		Context context = ContextUtil.getInstance();
		myInput = context.getResources().getAssets().open(filename);
		byte[] buffer = new byte[1024];
		int length = myInput.read(buffer);
		while(length > 0)
		{
			myOutput.write(buffer, 0, length);
			length = myInput.read(buffer);
		}

		myOutput.flush();
		myInput.close();
		myOutput.close();
	}

	public static boolean copyFile(String oldPathName, String newPathName) {
		try {
			File oldFile = new File(oldPathName);
			if (!oldFile.exists()) {
				Log.e("--Method--", "copyFile:  oldFile not exist.");
				return false;
			} else if (!oldFile.isFile()) {
				Log.e("--Method--", "copyFile:  oldFile not file.");
				return false;
			} else if (!oldFile.canRead()) {
				Log.e("--Method--", "copyFile:  oldFile cannot read.");
				return false;
			}

            /* 如果不需要打log，可以使用下面的语句
            if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
                return false;
            }
            */

			FileInputStream fileInputStream = new FileInputStream(oldPathName);
			FileOutputStream fileOutputStream = new FileOutputStream(newPathName);
			byte[] buffer = new byte[1024];
			int byteRead;
			while (-1 != (byteRead = fileInputStream.read(buffer))) {
				fileOutputStream.write(buffer, 0, byteRead);
			}
			fileInputStream.close();
			fileOutputStream.flush();
			fileOutputStream.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static String getWhatsNewText()
	{
		Context context = ContextUtil.getInstance();
		String res = "";

		try
		{
			InputStream in = context.getResources().getAssets()
					.open("whatsnew.txt");
			int length = in.available();
			byte[] buffer = new byte[length];
			in.read(buffer);
			res = new String(buffer,"GB2312");
		} catch (Exception e)
		{
			res = "";
		}

		return res;
	}

}
	

