;
/*************************************************************
 *
 * Copyright (c) 2022 ysrock Co., Ltd.	<info@ysrock.co.jp>
 * Copyright (c) 2022 Yasuo Sugano	<sugano@ysrock.co.jp>
 *
 * Version	: 1.0.0
 * Update	  : 2022.12.30
 *
 ************************************************************/
'use strict';

window['code2address'] = function( code ){
  if (!code.match(/^(\d{3})-?(\d{4})$/)) return;
  const code1 = RegExp.$1;
  const code2 = RegExp.$2;
  code = String(code1) + String(code2);

  const scriptDir = (function(){
    const scripts = document.getElementsByTagName('script');
    for (let i=0,len=scripts.length; i<len; i++){
      if (!scripts[i].src.match(/zipcode\.js/)) continue;
      return scripts[i].src.substr( 0, scripts[i].src.lastIndexOf('/') );
    };
  })();

  const result = (async () => {
    return await new Promise( (resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', scriptDir + "/json/" + code1 + ".json");
      xhr.addEventListener('load', (e) => {
        if (xhr.readyState != 4 || xhr.status != 200 ) reject( xhr );
        let ary = JSON.parse( xhr.responseText );
        for (let i=0,len=ary.length; i<len; i++){
          if (ary[i][0] != code) continue;
          resolve( ary[i] );
        };
        reject( xhr );
      });
      xhr.send();
    });
  })();
  return result;
};