import 'dart:math';

class Image {
  String id;
  String userId;
  String subjectId;
  String src;
  String srcType;
  String thumbnail;
  String seq;
  String createdAt;
  int w = 0, h = 0;

  Image({this.id, this.userId, this.subjectId, this.src, this.srcType, this.thumbnail, this.seq, this.createdAt});

  Image.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    userId = json['user_id'];
    subjectId = json['subject_id'];
    src = json['src'];
    srcType = json['src_type'];
    thumbnail = json['thumbnail'];
    seq = json['seq'];
    createdAt = json['created_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['user_id'] = this.userId;
    data['subject_id'] = this.subjectId;
    data['src'] = this.src;
    data['src_type'] = this.srcType;
    data['thumbnail'] = this.thumbnail;
    data['seq'] = this.seq;
    data['created_at'] = this.createdAt;
    return data;
  }

  static RegExp reg = new RegExp(r"_size([0-9]+)x([0-9]+)");

  double getImageAspectRatio() {
    String url = this.src;
    if (url?.isNotEmpty == true) {
      if (this.w == 0 || this.h == 0) {
        var match = reg.firstMatch(url);
        if (match != null) {
          this.w = int.parse(match.group(1));
          this.h = int.parse(match.group(2));
        }
      }
      if (this.w != 0 && this.h != 0) {
        // print("$url  w:${this.w},h:${this.h},a:${this.w / this.h}");
        return this.w / this.h;
      }
    }
    return 1.5;
  }

  double getWidth(double width){
    if(getImageAspectRatio() > 16 / 10)
      return width;
    double height = width / max(16 / 10, getImageAspectRatio());
    double r = height / h * w;
    // double r1 =  min(w / width * h, width);
    double fix = max(r, width / 3);
    // print("$width $height ${getImageAspectRatio()} $r  --  $w $h $fix");
    return r;
  }

  bool isLongImage(){
    double s = w / h;
    return s < 0.2 || s > 3;
  }
}
