package xmltojava;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class XmlToJava {

    private static boolean isFont = false;
    private static boolean isTypedValue = false;
    private static boolean isColor = false;
    private static Map<String, String> optionMap = new HashMap<>();
    static ArrayList<String> optionCode = new ArrayList<>();
    private static String[] fileNameValue = new String[3];
    private static String fileName = "";
    public static void main(String[] args) {

        String xml = "     <TextView\\n" +
                "            android:id=\\"@+id/shop_title\\"\\n" +
                "            android:layout_width=\\"wrap_content\\"\\n" +
                "            android:layout_height=\\"wrap_content\\"\\n" +
                "            android:layout_centerInParent=\\"true\\"\\n" +
                "            android:text=\\"텍스트!\\"\\n" +
                "            android:letterSpacing=\\"-0.03\\"\\n" +
                "            android:lineSpacingExtra=\\"4sp\\"\\n" +
                "            android:fontFamily=\\"@font/roboto_bold\\"\\n" +
                "            android:textColor=\\"#212121\\"\\n" +
                "            android:background=\\"@drawable/back_btn_arrow\\"\\n" +
                "            android:textSize=\\"20dp\\" />";
        xml = xml.replaceAll(" ","");
        String[] split = xml.split("\\nandroid:");
        for (int i = 1; i < split.length; i++) {
            String[] option = split[i].split("=");
            String returnOptionCode = getOptionJava(option[0],option[1].split("\\\\\\"")[1]);
            if (!returnOptionCode.isEmpty())
                optionCode.add(returnOptionCode);
            optionMap.put(option[0],option[1].split("\\\\\\"")[1]);
        }

        if (overlapCheck()) {
            System.out.println("중복된 클래스가 있습니다.");

        } else {
            makeTextView();

        }

    }

    public static void makeJavaFile(String data) {
        OutputStream output = null;
        try {
            output = new FileOutputStream("C:/Users/Beemo/test/test.java");
            byte[] by=data.getBytes();
            output.write(by);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static boolean overlapCheck() {

        String text = "";
        try{
            //파일 객체 생성
            File file = new File("C:/Users/Beemo/test/test.java");
            //입력 스트림 생성
            FileReader file_reader = new FileReader(file);
            int cur = 0;
            while((cur = file_reader.read()) != -1){
               // System.out.print((char)cur);
                text += (char)cur;
            }
            file_reader.close();
        }catch (FileNotFoundException e) {
            e.getStackTrace();
        }catch(IOException e){
            e.getStackTrace();
        }

        boolean result = true;
        for (int i = 0; i < optionCode.size(); i++) {
            if(!text.contains(optionCode.get(i))) {
                System.out.println(optionCode.get(i));
                System.out.println("here");
                result = false;
                break;
            }
        }
        return result;

    }
    public static boolean checkValid() {
        if (fileNameValue[1].isEmpty() || fileNameValue[2].isEmpty()) {
            return false;
        } else {
            return true;
        }
    }
    /*  if (fileNameValue[0].isEmpty()) {
                fileName = fileNameValue[1]+fileNameValue[2];
            } else {
                String[] camel = fileNameValue[0].split("_");
                if (97 <= camel[0].charAt(0) && camel[0].charAt(0) <= 122) {
                    char[] data = camel[0].toCharArray();
                    data[0] = (char)(data[0] - 32);
                    camel[0] = String.valueOf(data);

                }
                if (97 <= camel[1].charAt(0) && camel[1].charAt(0) <= 122) {
                    char[] data = camel[1].toCharArray();
                    data[0] = (char)(data[0] - 32);
                    camel[1] = String.valueOf(data);
                }
                fileName = camel[0]+camel[1]+fileNameValue[1]+fileNameValue[2];
                System.out.println("TextView" + fileName.replace("#",""));
            }*/
    public static String getOptionJava(String option, String optionValue) {

        String returnValue = "";
        if (option.equals("layout_width")) {
            returnValue = "getLayoutParams().width = ";
            if (optionValue.equals("wrap_content")) {
                returnValue = returnValue + "ViewGroup.LayoutParams.WRAP_CONTENT;";
            } else if (optionValue.equals("match_parent")) {
                returnValue = returnValue + "ViewGroup.LayoutParams.MATCH_PARENT;";
            } else if (optionValue.contains("dp")) {
                isTypedValue = true;
                returnValue = returnValue + " (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, "+optionValue.replace("dp","")+", getResources().getDisplayMetrics());";
            } else {
                returnValue = returnValue + "\\""+optionValue+"\\"";
            }
        } else if (option.equals("layout_height")) {
            returnValue = "getLayoutParams().height = ";
            if (optionValue.equals("wrap_content")) {
                returnValue = returnValue + "ViewGroup.LayoutParams.WRAP_CONTENT;";
            } else if (optionValue.equals("match_parent")) {
                returnValue = returnValue + "ViewGroup.LayoutParams.MATCH_PARENT;";
            } else if(optionValue.contains("dp")) {
                isTypedValue = true;
                returnValue = returnValue + " (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, "+optionValue.replace("dp","")+", getResources().getDisplayMetrics());";
            } else {
                returnValue = returnValue + "\\""+optionValue+"\\"";
            }

        } else if (option.equals("textSize")) {
            isTypedValue = true;
            if (optionValue.contains("dp")) {
                returnValue = "setTextSize(TypedValue.COMPLEX_UNIT_DIP,"+optionValue.replace("dp","")+");";
            } else if (optionValue.contains("sp")) {
                returnValue = "setTextSize(TypedValue.COMPLEX_UNIT_SP,"+optionValue.replace("sp","")+");";
            }
        } else if (option.equals("background")) {
            if (optionValue.contains("#")) {
                isColor = true;
                returnValue = "setBackgroundColor(Color.parseColor(\\""+optionValue+"\\"));";
            } else if(optionValue.contains("drawable")) {
                returnValue = "setBackgroundResource(R.drawble."+optionValue.replace("@drawable/","")+");";
            } else if(optionValue.contains("mipmap")) {
                returnValue = "setBackgroundResource(R.mipmap."+optionValue.replace("@mipmap/","")+");";
            }
        } else if (option.equals("textColor")) {
            if (optionValue.contains("#")) {
                isColor = true;
                returnValue = "setTextColor(Color.parseColor(\\""+optionValue+"\\"));";
            }
        } else if (option.equals("fontFamily")) {
            isFont = true;
            returnValue = "Typeface typeface = Typeface.createFromAsset(context.getAssets(),\\"font/"+optionValue.replace("@font/","")+".ttf\\");";
        } else if (option.equals("letterSpacing")) {
            returnValue = "setLetterSpacing("+optionValue+"f);";
        } else if (option.equals("lineSpacingExtra")) {
            isTypedValue = true;
            if (optionValue.contains("dp")) {
                returnValue = "setLineSpacing(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,"+optionValue.replace("dp","")+",getResources().getDisplayMetrics()),1);";
            } else if (optionValue.contains("sp")) {
                returnValue = "setLineSpacing(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,"+optionValue.replace("sp","")+",getResources().getDisplayMetrics()),1);";
            }
        }

        return returnValue;
    }

    public static void makeTextView() {
        String classText = "import android.content.Context;\\n" +
                "import android.util.AttributeSet;\\n" +
                "import android.view.ViewGroup;\\n";

        if (isFont) {
            isFont = false;
            classText = classText + "import android.graphics.Typeface;\\n";
        }
        if (isTypedValue) {
            isTypedValue = false;
            classText = classText + "import android.util.TypedValue;\\n";
        }

        if (isColor) {
            isColor = false;
            classText = classText + "import android.graphics.Color;\\n";
        }

        classText = classText+"\\npublic class CustomTextView extends androidx.appcompat.widget.AppCompatTextView {\\n" +
                "\\tpublic CustomTextView(Context context) {\\n" +
                "\\t\\tsuper(context);";

        String setOptionCode = "";
        for(int i = 0; i < optionCode.size(); i++) {
            if (optionCode.get(i).equals(""))
                continue;
            setOptionCode = setOptionCode +"\\n\\t\\t"+optionCode.get(i);
        }
        classText = classText + setOptionCode + "\\n\\t"+"}";

        classText = classText + "\\n\\n" +
                "\\tpublic CustomTextView(Context context, AttributeSet attrs) {\\n" +
                "\\t\\tsuper(context, attrs);";

        classText = classText + setOptionCode + "\\n\\t"+"}";

        classText = classText + "\\n\\n" +
                "\\tpublic CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {\\n" +
                "\\t\\tsuper(context, attrs, defStyleAttr);";

        classText = classText + setOptionCode + "\\n\\t" + "}\\n}";
        makeJavaFile(classText);//.java 파일 생성
        System.out.println(classText);
    }
}
/**
 *   done
 * - 마진, 패딩 셋팅 - 마진, 패딩은 화면마다 다르게 적용될 수 있음, 공통클래스로 적합하지않음 - 생략
 * - 폰트, 자간 등 옵션 셋팅 - 폰트, 자간, 줄간격 완료
 * - import 추가 - 완료
 * - background xml 파일 적용하기 - 완료
 * - .java파일 추출 - 완료
 * - 중복 클래스 체크
 */
/**
 *   todo
 * - 패키지명 가져오기, xml파일 적용을 위한 R import 에도 필요
 * - UI
 */