package com.chenyang.nse.bussiness.engine.infa.powercenter961.pubbean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class ModifyImportFile {
   public static void updateConfigFileXML(String tagname, File file, String foldername) throws Exception {
      Document document = getDocumentByFile(file);
      List<Element> firstLevelElements = getFirstLevelElements(document);

      for(int i = 0; i < firstLevelElements.size(); ++i) {
         List<Attribute> attrs = ((Element)firstLevelElements.get(i)).getAttributes();

         for(int j = 0; j < attrs.size(); ++j) {
            if (((Attribute)attrs.get(j)).getName().equals(tagname)) {
               ((Attribute)attrs.get(j)).setValue(foldername);
               writeToFile(document, file);
            }
         }
      }

   }

   private static Document getDocumentByFile(File file) {
      SAXBuilder builder = new SAXBuilder();
      Document document = null;

      try {
         document = builder.build(file);
      } catch (JDOMException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      return document;
   }

   private static List<Element> getFirstLevelElements(Document document) {
      Element root = document.getRootElement();
      List<Element> firstLevelElements = root.getChildren();
      return firstLevelElements;
   }

   private static void writeToFile(Document document, File file) {
      XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
      OutputStream os = null;

      try {
         os = new FileOutputStream(file);
         out.output(document, os);
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         try {
            os.close();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }
}
