package com.palacesun.masking.tools;

import java.util.ArrayList;
import java.util.List;

public class InsertSqlVaulesUtil {
   public static List<Object> getTableColumnValueByMatchingSingleQuotes(Object[] targetArray) {
       List tableColumnValueList = new ArrayList();
       for(int i = 0; i < targetArray.length; ++i) {
           Object columnValue = targetArray[i];
           int endIndex = i;
           boolean result = judgeMatchingSingleQuotes(columnValue);
           if (!result) {
               ++i;
               endIndex = getMatchingSingleQuotesIndex(targetArray, i);
           }

           if (endIndex != i && endIndex != -999) {
               for(int j = i + 1; j <= endIndex; ++j) {
                   columnValue = columnValue + "," + targetArray[j];
               }

               i = endIndex;
           }

           tableColumnValueList.add(columnValue);
       }

       return tableColumnValueList;
   }

   public static int getMatchingSingleQuotesIndex(Object[] targetArray, int startIndex) {
      for(int i = startIndex; i < targetArray.length; ++i) {
         boolean result = judgeMatchingSingleQuotes(targetArray[i]);
         if (!result) {
            return startIndex;
         }

         ++startIndex;
      }

      return -999;
   }

   public static boolean judgeMatchingSingleQuotes(Object target) {
      char[] chars = target.toString().toCharArray();
      int quotesCount = 0;

      for(int i = 0; i < chars.length; ++i) {
         if (chars[i] == '\'') {
            ++quotesCount;
         }
      }

      return quotesCount % 2 == 0;
   }

   public static void main(String[] args) {
      String str = "'ABCD', 'EFG','HIJK','LMNOPQ','abc ''def (ghij, ''klmn'', ''kokoio'')','uuywe','fasf','N'";
      getTableColumnValueByMatchingSingleQuotes(str.split(","));
   }
}
