import hipparcos_catalog from "./hipparcos_7_concise.js";
import CatalogSkybox from "./CatalogSkybox.js";

function createSkyboxImage(faceId0, width) {
  //  恒星亮度（等级）,亮度等级越小，亮度越大
  const magBright = -1;
  const magMedium = 7;
  const magDim = 12;
  //  恒星大小，单位像素
  const sizeBright = 5;
  const sizeMedium = 1;
  const sizeDim = 0.1;
  //  恒星透明度(1为不透明，0为透明)
  const translucentBright = 1.0;
  const translucentMedium = 0.5;
  const translucentDim = 0.2;

  const d2r = Math.PI / 180;

  //  创建width*width的jpg格式的图片，背景为黑色，随机生成1000个像素点，颜色为白色，大小从1到5像素不等
  var canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = width;
  var context = canvas.getContext("2d");
  //  黑色背景
  context.fillStyle = "black";
  context.fillRect(0, 0, width, width);

  //  循环hipparcos数据,hipparcos_catalog为数组
  for (var id = 0; id < hipparcos_catalog.length; id++) {
    var star = hipparcos_catalog[id];
    var mag = star[1];
    var ra = star[2];
    var dec = star[3];

    //  赤经、赤纬转换为弧度
    if (ra > 180) {
      ra = ra - 360;
    }
    ra = ra * d2r;
    dec = dec * d2r;

    //  赤经、赤纬转换为立方盒子坐标，再转换为图片坐标
    let { x, y, z } = CatalogSkybox.sphere2CubeXyz(ra, dec);

    //  转换为图片坐标（i,为横坐标，向右,[0,1]), (j为纵坐标,向下,[0,1])
    let { i, j, faceId } = CatalogSkybox.cubeXyzToImgUV(x, y, z);

    if (faceId !== faceId0) {
      continue;
    }

    //  像素大小
    let size = sizeBright;
    let translucent = translucentBright;
    if (mag > magBright && mag <= magMedium) {
      size =
        sizeMedium +
        ((sizeBright - sizeMedium) * (mag - magMedium)) /
          (magBright - magMedium);
      translucent =
        translucentMedium +
        ((translucentBright - translucentMedium) * (mag - magMedium)) /
          (magBright - magMedium);
    }
    //  亮度太暗，最小值
    else if (mag > magMedium) {
      size = sizeDim;
      translucent = translucentDim;
    }

    if (mag < 1) {
      console.log(mag, size, translucent);
    }

    //  图像坐标系下的坐标
    let u = i * width - size / 2;
    let v = j * width - size / 2;
    if (u < 0) {
      u = 0;
    }
    if (v < 0) {
      v = 0;
    }

    //  画点,白色，带透明度
    context.fillStyle = `rgba(255,255,255,${translucent})`;
    context.fillRect(u, v, size, size);
  }

  var dataUrl = canvas.toDataURL("image/jpeg");

  //  将这个图片插入到id为img1的img元素中
  //var img1 = document.getElementById('img1');
  //img1.src = dataUrl;

  return dataUrl;
  var image = new Image();
  image.src = dataUrl;

  return image;
  //  将这个图片插入到id为img1的img元素中
  //var img1 = document.getElementById('img1');
  //img1.src = dataUrl;
}

export default createSkyboxImage;
