/**
 * Copyright (c) 2003-2014 Beauty Garage Inc.
 *                 All Rights Reserved.
 */
package jp.co.sint.basic;

import java.util.ArrayList;
import java.util.Collection;
import org.w3c.dom.*;
import java.io.*;
import java.net.*;

import jp.co.sint.tools.SIUtil;
import jp.co.sint.tools.SICheckUtil;
import jp.co.sint.tools.SIHTMLUtil;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class SINaviplusSearch extends SIBasic {
  
  //requestパラメータ
  private String q = "";
  private String exq = "";
  private String[] f = null;
  private String i = "";
  private String t = "";
  private String tb = "";
  private String d = "";
  private String[] k = new String[20];
  private String[] kb = new String[20];
  private String path = "";
  private String[][] s = new String[20][20];
  private String[] so = new String[20];
  private String[] sa = new String[20];
  private String[] sb = new String[20];
  private String[] nl = new String[20];
  private String[] nh = new String[20];
  private String[] nc = new String[20];
  private String pl = "";
  private String ph = "";
  private String o = "";
  private String limit = "";
  private String sort = "Score";
  private String style = "";
  private String searchbox = "";
  private String ichar = "";
  private String fmt = "xml";
  private String callback = "";
  
  //responceパラメータ
  private String hitnum = "";
  
  public SINaviplusSearch(){
    for (int count1=0;count1<20;count1++) {
      k[count1] = "";
      kb[count1] = "";
      for (int count2=0;count2<20;count2++) {
        s[count1][count2] = "";
      }
      so[count1] = "";
      sa[count1] = "";
      sb[count1] = "";
      nl[count1] = "";
      nh[count1] = "";
      nc[count1] = "";
    }
  }
  
  public String getSendParameter(){
    StringBuffer str = new StringBuffer();
    str.append("?q=").append(SIHTMLUtil.URLEncode(q));
    if (SIUtil.isNotNull(exq)) str.append("&exq=").append(SIHTMLUtil.URLEncode(exq));
    if (f!=null && f.length>0) {
      for (int count1=0;count1<f.length;count1++) {
        str.append("&f[]=").append(f[count1]);
      }
    }
    if (SIUtil.isNotNull(i)) str.append("&i=").append(i);
    if (SIUtil.isNotNull(t)) str.append("&t=").append(t);
    if (SIUtil.isNotNull(tb)) str.append("&tb=").append(tb);
    if (SIUtil.isNotNull(d)) str.append("&d=").append(d);
    if (SIUtil.isNotNull(path)) str.append("&path=").append(path);
    for (int count2=0;count2<20;count2++) {
      if (SIUtil.isNotNull(k[count2])) str.append("&k").append(String.valueOf(count2+1)).append("=").append(k[count2]);
      if (SIUtil.isNotNull(kb[count2])) str.append("&k").append(String.valueOf(count2+1)).append("b=").append(kb[count2]);
      for(int count3=0;count3<20;count3++) {
        if (SIUtil.isNotNull(s[count2][count3])) str.append("&s").append(String.valueOf(count2+1)).append("[]=").append(s[count2][count3]);
      }
      if (SIUtil.isNotNull(so[count2])) str.append("&s").append(String.valueOf(count2+1)).append("o=").append(so[count2]);
      if (SIUtil.isNotNull(sa[count2])) str.append("&s").append(String.valueOf(count2+1)).append("a=").append(sa[count2]);
      if (SIUtil.isNotNull(sb[count2])) str.append("&s").append(String.valueOf(count2+1)).append("b=").append(sb[count2]);
      if (SIUtil.isNotNull(nl[count2])) str.append("&n").append(String.valueOf(count2+1)).append("l=").append(nl[count2]);
      if (SIUtil.isNotNull(nh[count2])) str.append("&n").append(String.valueOf(count2+1)).append("h=").append(nh[count2]);
      if (SIUtil.isNotNull(nc[count2])) str.append("&n").append(String.valueOf(count2+1)).append("c=").append(nc[count2]);
    }
    if (SIUtil.isNotNull(pl)) str.append("&pl=").append(pl);
    if (SIUtil.isNotNull(ph)) str.append("&ph=").append(ph);
    if (SIUtil.isNotNull(o)) str.append("&o=").append(o);
    if (SIUtil.isNotNull(limit)) str.append("&limit=").append(limit);
    if (SIUtil.isNotNull(sort)) str.append("&sort=").append(sort);
    if (SIUtil.isNotNull(style)) str.append("&style=").append(style);
    if (SIUtil.isNotNull(searchbox)) str.append("&searchbox=").append(searchbox);
    if (SIUtil.isNotNull(ichar)) str.append("&ichar=").append(ichar);
    if (SIUtil.isNotNull(fmt)) str.append("&fmt=").append(fmt);
    if (SIUtil.isNotNull(callback)) str.append("&callback=").append(callback);
    return str.toString();
  }
  
  public Collection getCollection(SIUserInfo lUserInfo,String taxRate){
    Collection res = new ArrayList();
    StringBuffer str = new StringBuffer();
    try{
      URL url = new URL("http://std2f-s.snva.jp/~beautygarage/" + this.getSendParameter()); 
      HttpURLConnection con = (HttpURLConnection)url.openConnection();
      con.setRequestMethod("GET");
      con.setDoOutput(true);
      con.setInstanceFollowRedirects(false);
      con.setRequestProperty("Accept-Language", "jp"); 
      con.setRequestProperty("Authorization", "Basic YmVhdXR5Z2FyYWdlOmtvdG9oYWNvZGVtbw==");
      con.connect();
      PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(con.getOutputStream(),"utf-8")));
      pw.close();
      // body部の文字コード取得
      String contentType = con.getHeaderField("Content-Type");
      String charSet     = "Shift-JIS";//"ISO-8859-1";
      String[] elm = contentType.split(";");
      for(int i=0;i<elm.length;i++) {
        if (elm[i].trim().startsWith("charset=")) {
          charSet = elm[i].trim().substring(8);
          break;
        }
      }  
      // body部受信
      BufferedReader br;
      try{
        br = new BufferedReader(new InputStreamReader(con.getInputStream(),charSet));
      }
      catch(Exception e_){
        System.out.println( con.getResponseCode()+" "+ con.getResponseMessage() );
        br = new BufferedReader(new InputStreamReader(con.getErrorStream(),charSet));
      }
      String line;
      while ((line = br.readLine()) != null) {
        str.append(line);
      }
      br.close();
      con.disconnect(); 
      
      DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docbuilder = dbfactory.newDocumentBuilder();
      Document doc = docbuilder.parse(new ByteArrayInputStream(str.toString().getBytes("UTF-8")));
      
      this.setLimit(this.getNode(doc.getFirstChild().getFirstChild().getChildNodes().item(2).getChildNodes(), "limit").getFirstChild().getNodeValue());
      this.setO(this.getNode(doc.getFirstChild().getFirstChild().getChildNodes().item(2).getChildNodes(), "o").getFirstChild().getNodeValue());
      this.setHitnum(doc.getFirstChild().getChildNodes().item(1).getFirstChild().getChildNodes().item(2).getFirstChild().getNodeValue());
      if (SIUtil.isNull(this.getO())) this.setO("0");
      for (int count=0;count<Integer.parseInt(this.getO());count++){
        res.add(null);
      }
      NodeList cmdtyList = doc.getFirstChild().getChildNodes().item(1).getChildNodes().item(1).getChildNodes();
      for (int i=0;i<cmdtyList.getLength();i++){
        SICmdty lCmdty = new SICmdty();
        lCmdty.setTaxRate(taxRate);
        boolean contractFlg = true;
        NodeList cmdtyValue = cmdtyList.item(i).getChildNodes();
        for (int j=0;j<cmdtyValue.getLength();j++){
          Node cmdtyValueDetail = cmdtyValue.item(j);
          String name = cmdtyValueDetail.getNodeName();
          String value = "";
          if (cmdtyValueDetail.hasChildNodes()) value = cmdtyValueDetail.getFirstChild().getNodeValue();
          if ("itemid".equals(name)) {
            lCmdty.setIndividualCode(value);
            for (int k=0;k<lUserInfo.getMycatalog().length;k++){
              if (value.equals(lUserInfo.getMycatalog()[k])) lCmdty.setMycatalogFlg("1");
            }
          }
          else if ("title".equals(name)) lCmdty.setCmdtyName(value);
          else if ("price".equals(name)) {
            lCmdty.setUnitPrice(value);
            lCmdty.setCalcUnitPrice(value);
          } else if ("narrow4".equals(name)) {
            lCmdty.setMakerCode(value);
            for (int l=0;l<lUserInfo.getMaker().length;l++){
              if (value.equals(lUserInfo.getMaker()[l])) contractFlg=false;
            }
          }
          else if ("narrow6".equals(name)) lCmdty.setUsedNewFlg(Integer.parseInt(value));
          else if ("data1".equals(name)) lCmdty.setCmdtyCode(value);
          else if ("data2".equals(name)) lCmdty.setNewFixedPrice(value);
          else if ("data3".equals(name)) lCmdty.setCampaignPriceFlg(value);
          else if ("data4".equals(name)) lCmdty.setPriceDownFlg(value);
          else if ("data5".equals(name)) lCmdty.setFreeDeliveryFlg(value);
          else if ("data6".equals(name)) lCmdty.setBGPriceDispFlg(value);
          else if ("data7".equals(name)) lCmdty.setCmdtyCompositionFlg(value);
          else if ("data8".equals(name)) lCmdty.setInquiryFlg(value);
          else if ("data9".equals(name)) lCmdty.setRsrvEnableFlg(value);
          else if ("data10".equals(name)) lCmdty.setRsrvAmount(value);
          else if ("data11".equals(name)) {
            if (contractFlg) contractFlg = !value.equals("0");
            lCmdty.setContractFlg(contractFlg);
          }
          else if ("data12".equals(name)) lCmdty.setAmount(value);
          else if ("data13".equals(name)) lCmdty.setPointRate(value);
          else if ("data14".equals(name)) lCmdty.setNomalPointRate(value);
          else if ("data15".equals(name)) lCmdty.setSpecialRate(value);
          else if ("data16".equals(name)) lCmdty.setAmountFlg(value);
          else if ("data17".equals(name)) lCmdty.setMemberDiscountFlg(value);
          else if ("data18".equals(name)) lCmdty.setNewArrivalFlg(value);
          else if ("data19".equals(name)) lCmdty.setUnitPriceWithoutTax(value);
        }
        lCmdty.setMemberDiscountRate(lUserInfo.getDiscountRate());
        if ("H".equals(lCmdty.getIndividualCode().substring(0,1))||"V".equals(lCmdty.getIndividualCode().substring(0,1))||"L".equals(lCmdty.getIndividualCode().substring(0, 1))){
          if ("1".equals(lUserInfo.getHairCosmeFlg())) {
            lCmdty.setHairCosmeFlg(false);
          }else{
            lCmdty.setHairCosmeFlg(true);
            lCmdty.setContractFlg(true);
          }
        }else{
          lCmdty.setHairCosmeFlg(false);
        }
        res.add(lCmdty);
      }
      if (SICheckUtil.isGreater(this.getHitnum(),SIUtil.add(this.getO(),this.getLimit()))) {
        for (int count2=0;count2<Integer.parseInt(SIUtil.sub(this.hitnum, SIUtil.add(this.getO(),this.getLimit())));count2++){
          res.add(null);
        }
      }
    }
    catch(Exception e){
      e.printStackTrace(System.err);
    }
    
    return res;
  }
  
  public String getQ() {return q;}
  public String getExq() {return exq;}
  public String getI() {return i;}
  public String getT() {return t;}
  public String getTb() {return tb;}
  public String getD() {return d;}
  public String[] getK() {return k;}
  public String getK(int count) {return k[count];}
  public String[] getKb() {return kb;}
  public String getKb(int count) {return kb[count];}
  public String getPath() {return path;}
  public String[][] getS() {return s;}
  public String getS(int count1,int count2) {return s[count1][count2];}
  public String[] getSo() {return so;}
  public String getSo(int count) {return so[count];}
  public String[] getSa() {return sa;}
  public String getSa(int count) {return sa[count];}
  public String[] getSb() {return sb;}
  public String getSb(int count) {return sb[count];}
  public String[] getNl() {return nl;}
  public String getNl(int count) {return nl[count];}
  public String[] getNh() {return nh;}
  public String getNh(int count) {return nh[count];}
  public String[] getNc() {return nc;}
  public String getNc(int count) {return nc[count];}
  public String getPl() {return pl;}
  public String getPh() {return ph;}
  public String getO() {return o;}
  public String getLimit() {return limit;}
  public String getSort() {return sort;}
  public String getStyle() {return style;}
  public String getSearchbox() {return searchbox;}
  public String getIchar() {return ichar;}
  public String getFmt() {return fmt;}
  public String getCallback() {return callback;}
  public String getHitnum(){return hitnum;};
  public void setQ(String val){this.q=val;}
  public void setExq(String val) {this.exq=val;}
  public void setI(String val) {this.i=val;}
  public void setT(String val) {this.t=val;}
  public void setTb(String val) {this.tb=val;}
  public void setD(String val) {this.d=val;}
  public void setK(int count,String val) {this.k[count]=val;}
  public void setKb(int count,String val) {this.kb[count]=val;}
  public void setPath(String val) {this.path=val;}
  public void setS(int count1,int count2,String val) {this.s[count1][count2]=val;}
  public void setSo(int count,String val) {this.so[count]=val;}
  public void setSa(int count,String val) {this.sa[count]=val;}
  public void setSb(int count,String val) {this.sb[count]=val;}
  public void setNl(int count,String val) {this.nl[count]=val;}
  public void setNh(int count,String val) {this.nh[count]=val;}
  public void setNc(int count,String val) {this.nc[count]=val;}
  public void setPl(String val) {this.pl=val;}
  public void setPh(String val) {this.ph=val;}
  public void setO(String val) {this.o=val;}
  public void setLimit(String val) {this.limit=val;}
  public void setSort(String val) {this.sort=val;}
  public void setStyle(String val) {this.style=val;}
  public void setSearchbox(String val) {this.searchbox=val;}
  public void setIchar(String val) {this.ichar=val;}
  public void setFmt(String val) {this.fmt=val;}
  public void setCallback(String val) {this.callback=val;}
  public void setHitnum(String val){this.hitnum=val;};
  
  private Node getNode(NodeList list,String keyword){
    for (int i=0;i<list.getLength();i++){
      if (list.item(i).getNodeName().equals(keyword)) {
        return list.item(i);
      }
    }
    return null;
  }
}